给定一个 flexbox 容器,如果 child 有很多内容,我如何确保它们不会溢出容器?
.container {
display: flex;
flex-direction: column;
background-color: #ccc;
height: 210px;
width: 200px;
}
.child {
display: flex;
width: 100px;
}
.first {
background-color: rgba(255, 0, 0, 0.2);
}
.second {
background-color: rgba(0, 255, 0, 0.2);
}
.third {
background-color: rgba(0, 0, 255, 0.2);
}
<div class="container">
<div class="first child">first first first first first first first</div>
<div class="second child">second second second second second second second second second second second second second second second second second second second</div>
<div class="third child">third</div>
</div>
最佳答案
子元素会溢出父元素,因为它们的固有高度(内容的高度)大于父元素的高度。您可以通过在子元素上设置 min-height: 0
来建议浏览器忽略固有高度。如果您添加 overflow: hidden
,结果应该是您所期望的:
.container {
display: flex;
flex-direction: column;
background-color: #ccc;
height: 210px;
width: 200px;
}
.child {
width: 100px;
min-height: 0;
overflow: hidden;
}
.first {
background-color: rgba(255, 0, 0, 0.2);
}
.second {
background-color: rgba(0, 255, 0, 0.2);
}
.third {
background-color: rgba(0, 0, 255, 0.2);
}
<div class="container">
<div class="first child">first first first first first first first</div>
<div class="second child">second second second second second second second second second second second second second second second second second second second</div>
<div class="third child">third</div>
</div>
children 根据他们的内容高度按比例分配高度。 overflow hidden 的内容。
关于css - 如何强制 flex children 不溢出容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49325987/