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/

相关文章:

php - 包括标题页 session 错误

css - 使用 flexbox 垂直对齐具有不同尺寸图像的内容

html - 如何将元素包装在 flexbox 中以适应较小的屏幕?

twitter-bootstrap - 为什么 col-auto 中多列嵌套行的大小大于内容宽度?

css - 如何制作带有附加链接的 Flexbox Gallery Images 使它们成为 flex childs

html - 控制 Flexbox HTML CSS 中内容的宽度

javascript - 如何阻止在 Google Blogger 模板中加载 CSS 和 js 文件?

javascript - 单选按钮不会以 html 形式显示

python - Pandas 造型师。如何忽略呈现的 HTML 中的索引列

javascript - 如何在 div 的中心放置弹出消息?