我怎样才能有两个固定宽度的列,中间有一个灵活的列?

新手上路,请多包涵

我正在尝试设置一个具有三列的 flexbox 布局,其中左右列具有固定宽度,中间列弯曲以填充可用空间。

尽管为列设置了尺寸,但它们似乎仍会随着窗口缩小而缩小。

任何人都知道如何做到这一点?

我需要做的另一件事是根据用户交互隐藏右列,在这种情况下,左列仍将保持其固定宽度,但中间列将填充其余空间。

 #container {
    display: flex;
    justify-content: space-around;
    align-items: stretch;
    max-width: 1200px;
}

.column.left {
    width: 230px;
}

.column.right {
    width: 230px;
    border-left: 1px solid #eee;
}

.column.center {
    border-left: 1px solid #eee;
}
 <div id="container">
    <div class="column left">
        <p>Anxiety was a blog series that ran in the New York Times Opinion section from January 2012 to July 2013. It featured essays, fiction, and art by a wide range of contributors that explored anxiety from scientific, literary, and artistic perspectives.</p>
    </div>
    <div class="column center">
        <img src="http://i.imgur.com/60PVLis.png" width="100" height="100" alt="">
    </div>
    <div class="column right">
        Balint Zsako
        <br/> Someone’s Knocking at My Door
        <br/> 01.12.13
    </div>
</div>

这是一个 JSFiddle:http: //jsfiddle.net/zDd2g/185/

原文由 mheavers 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 222
2 个回答

您可以使用 flex: 0 0 230px; 而不是使用 width (这是使用 flexbox 时的建议),这意味着:

  • 0 = 不增长( flex-grow 的简写)
  • 0 = 不缩小( flex-shrink 的简写)
  • 230px = 从 230px flex-basis 简写)

这意味着:总是 230px

看小提琴,谢谢@TylerH

哦,你不需要 justify-contentalign-items 在这里。

 img {
    max-width: 100%;
}
#container {
    display: flex;
    x-justify-content: space-around;
    x-align-items: stretch;
    max-width: 1200px;
}
.column.left {
    width: 230px;
    flex: 0 0 230px;
}
.column.right {
    width: 230px;
    flex: 0 0 230px;
    border-left: 1px solid #eee;
}
.column.center {
    border-left: 1px solid #eee;
}

原文由 Rudie 发布,翻译遵循 CC BY-SA 4.0 许可协议

尽管为列设置了尺寸,但它们似乎仍会随着窗口缩小而缩小。

弹性容器的初始设置是 flex-shrink: 1 。这就是您的列缩小的原因。

无论您指定什么宽度( 它可以是 width: 10000px ),使用 flex-shrink 可以忽略指定的宽度,并且可以防止弹性项目溢出容器。

我正在尝试设置一个具有 3 列的 flexbox,其中左右列具有固定宽度…

您将需要禁用收缩。以下是一些选项:

 .left, .right {
     width: 230px;
     flex-shrink: 0;
 }

或者

.left, .right {
     flex-basis: 230px;
     flex-shrink: 0;
}

或者,按照规范的建议:

 .left, .right {
    flex: 0 0 230px;    /* don't grow, don't shrink, stay fixed at 230px */
}

7.2.灵活性的组成部分

鼓励作者使用 flex 速记而不是直接使用其普通属性来控制灵活性,因为速记可以正确地重置任何未指定的组件以适应 常见用途

此处有更多详细信息: flex-basis 和 width 之间有什么区别?

我需要做的另一件事是根据用户交互隐藏右列,在这种情况下,左列仍将保持其固定宽度,但中间列将填充其余空间。

尝试这个:

 .center { flex: 1; }

这将允许中心列占用可用空间,包括删除其兄弟项时的空间。

修改后的小提琴

原文由 Michael Benjamin 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题