在下面的示例中,我希望标头 ( h4.child-title
) 在父容器中具有相同的长度。
但我没有成功实现这一目标。
.top-level {
display: flex;
flex-flow: row wrap;
}
.section {
display: flex;
flex-flow: row nowrap;
border: 1px solid;
margin-right: 12px;
margin-top: 12px;
}
.section-child {
display: flex;
flex-flow: column nowrap;
align-items: center;
flex: 1 1 0;
}
.child-title {
white-space: nowrap;
}
.vertical-separator {
width: 1px;
background-color: rgba(0, 0, 0, 0.3);
margin: 8px;
}
<div class="top-level">
<section class="section">
<div claas="section-child">
<h4 class="child-title">Title</h4>
<!--A lot more content here-->
</div>
<div class="vertical-separator"></div>
<div class="section-child">
<h4 class="child-title">Longer title</h4>
<!--A lot more content here-->
</div>
<div class="vertical-separator"></div>
<div class="section-child">
<h4 class="child-title">Much much longer title</h4>
<!--A lot more content here-->
</div>
</section>
<section class="section">
<div claas="section-child">
<h4 class="child-title">Title</h4>
<!--A lot more content here-->
</div>
<div class="vertical-separator"></div>
<div class="section-child">
<h4 class="child-title">Longer title</h4>
<!--A lot more content here-->
</div>
<div class="vertical-separator"></div>
<div class="section-child">
<h4 class="child-title">Much much longer title</h4>
<!--A lot more content here-->
</div>
</section>
<section class="section">
<div claas="section-child">
<h4 class="child-title">Title</h4>
<!--A lot more content here-->
</div>
<div class="vertical-separator"></div>
<div class="section-child">
<h4 class="child-title">Longer title</h4>
<!--A lot more content here-->
</div>
<div class="vertical-separator"></div>
<div class="section-child">
<h4 class="child-title">Much much longer title</h4>
<!--A lot more content here-->
</div>
</section>
</div>
原文由 Ashok Koyi 发布,翻译遵循 CC BY-SA 4.0 许可协议
弹性盒方法
为了使文本项 (
.section-child
) 等宽,您需要使用flex: 1 1 0
,您已经完成了。这与说flex: 1
是一样的。但是,这本身并不能实现目标,原因有二:
.section-child
的父级,一个 flex 容器,也是一个更大容器中的 flex 项目,默认情况下限制为其内容的宽度。所以它不会展开并且文本会溢出容器。您还需要将flex: 1
应用到.section
。默认情况下,弹性项目不能小于其内容的大小。初始设置为
min-width: auto
。所以flex: 1
不能平均分配容器空间,因为弹性项目不能收缩超过最长的项目。您需要使用min-width: 0
覆盖此行为。现在所有的弹性项目都是等宽的。但是,因为您将文本设置为
nowrap
,它可能会溢出其边界。如果你删除nowrap
,一切都很合适。更多信息:
CSS 网格方法
如果您的实际目标是使行中的所有弹性项目等于最长项目的宽度,那是 flexbox 无法做到的。
flex可以做等宽等高的flex items,因为它在主轴上提供了
flex: 1
。Flex也可以做等宽等高的列/行,因为它在横轴上提供了
align-items: stretch
。但是 flexbox 规范中没有关于基于特定兄弟大小的相等大小 flex 项目的任何内容。但是,flexbox 的姊妹技术 CSS Grid 可以做到。
通过使用 Grid 的
fr
单元,可以将网格中的列宽设置为最长列的宽度。它是这样工作的: