首页 > 解决方案 > 等高子元素将其姐妹元素推出父容器

问题描述

我正在尝试并排放置两个元素 (.child1和) 并使它们的高度相等。.child3我为此使用 flex 和 height:100% 。但是,这会将姐妹元素 (.child2.child4) 推出父容器。我如何确保所有孩子都留在他们的.parent容器中?是否有没有 HTML 更改的纯 CSS 解决方案?

.container {
  display: flex;
}
.parent {
  background: blue;
  padding: 1rem;
  display: flex;
  flex-wrap: wrap;
}
.child1, .child3 {
  background: red;
  height: 100%;
  width: 100%;
}
.child2, .child4 {
  background: yellow;
  width: 100%;
  height: 50px;
}
<div class="container">
  <div class="parent">
    <div class="child1">Child 1 should have same height as Child 3</div>
    <div class="child2">Child 2 pushed out of parent. Has a fixed height.</div>
  </div>
  <div class="parent">
    <div class="child3">Child 3 should have same height as Child 1, even when one of the two has more content in it than the other. </div>
    <div class="child4">Child 4 pushed out of parent. Has a fixed height.</div>
  </div>
</div>

标签: htmlcss

解决方案


在您的元素中删除flex-wrap: wrap并替换它。然后从和中删除。flex-direction: column;.parentheight.child1.child3

.container {
  display: flex;
}
.parent {
  background: blue;
  padding: 1rem;
  display: flex;
  flex-direction: column;
}
.child1, .child3 {
  background: red;
  width: 100%;
}
.child2, .child4 {
  background: yellow;
  height: 50px;
}
<div class="container">
  <div class="parent">
    <div class="child1">Child 1 should have same height as Child 3</div>
    <div class="child2">Child 2 pushed out of parent. Has a fixed height.</div>
  </div>
  <div class="parent">
    <div class="child3">Child 3 should have same height as Child 1, even when one of the two has more content in it than the other. </div>
    <div class="child4">Child 4 pushed out of parent. Has a fixed height.</div>
  </div>
</div>

编辑:

如果它不能为您服务,那么您还必须更改 HTML

.container {
  display: flex;
  flex-wrap: wrap;
  background: blue;
  padding: 1rem;
  justify-content: space-between;
}

div[class^="child"]{
  flex: 0 0 Calc(50% - 10px);
}

.child1, .child3 {
  background: red;
}

.child2, .child4 {
  background: yellow;
  height: 50px;
}

.divider {
  width: 100%;
  flex: 0 0 100%;
}
<div class="container">
  <div class="child1">Child 1 should have same height as Child 3</div>
  <div class="child3">Child 3 should have same height as Child 1, even when one of the two has more content in it than the other. Child 3 should have same height as Child 1, even when one of the two has more content in it than the other. Child 3 should have same height as Child 1, even when one of the two has more content in it than the other. Child 3 should have same height as Child 1, even when one of the two has more content in it than the other. </div>
        
  <div class="divider"></div>
        
  <div class="child2">Child 2 pushed out of parent. Has a fixed height.</div>
  <div class="child4">Child 4 pushed out of parent. Has a fixed height.</div>
</div>


推荐阅读