css - 如何强制 flex children 不溢出容器?

标签 css flexbox

给定一个 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>

enter image description here

最佳答案

子元素会溢出父元素,因为它们的固有高度(内容的高度)大于父元素的高度。您可以通过在子元素上设置 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/

相关文章:

html - 边界问题

javascript - 在 Plotly.js 图表中的图例(或键)下方添加按钮

css - 使用 Angular 5 和 Flex 布局的 Div 之间的距离相等

css - 如果指定了文本溢出,浏览器如何计算 flexbox 的宽度

css - 将元素放在全屏 flexbox 的中心和右下角?

html - 获取显示 :flex to behave like display:inline-block

css - SVG 图像底部边框

javascript - jQuery : Select last element which content is

html - 视频/图像最大化ascii符号?

css - 折叠 Flexbox child 的边距