【问题标题】:How do I set parent div height based on height of tallest child?如何根据最高孩子的高度设置父 div 高度?
【发布时间】:2018-10-24 10:53:10
【问题描述】:

我有一行和两列(在本例中一列将是 flex)。我想将行的高度设置为最高子元素的高度。如果没有明确设置行的高度,我在执行此操作时遇到了麻烦。

.row {
  background: yellow;
}

.column1 {
  float: left;
  width: 50%;
}
.column2 {
  float: left;
  width: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  background: aqua;
}

img {
  width: 100%;
}
<div class="row">
  <div class="column1">
    <img src="https://hypb.imgix.net/image/2017/12/kith-spongebob-squarepants-teaser-1.jpg?q=75&w=800&fit=max&auto=compress%2Cformat">
  </div>
  <div class="column2">
    <p>This column should match the height of the other column</p>
  </div>
</div>

如何使父 div(.row) 的高度成为最高子 div 的高度(上例中的图像)?

任何帮助表示赞赏,

谢谢

附言我看到了这个资源equal height columns in css,但肯定有更简单的方法吗?

【问题讨论】:

    标签: html css sass flexbox


    【解决方案1】:

    在行中使用display:flex。如果将 flex 赋予父级,则无需将 float 属性赋予子级。

    .row {
      background: yellow;
      display: flex;
    }
    
    .column1 {
    
      width: 50%;
    }
    .column2 {
    
      width: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      background: aqua;
    }
    
    img {
      width: 100%;
    }
    <div class="row">
      <div class="column1">
        <img src="https://hypb.imgix.net/image/2017/12/kith-spongebob-squarepants-teaser-1.jpg?q=75&w=800&fit=max&auto=compress%2Cformat">
      </div>
      <div class="column2">
        <p>This column should match the height of the other column</p>
      </div>
    </div>

    【讨论】:

    • 谢谢!很高兴我问到,这并不像我想象的那么复杂。
    • 是的,它并不复杂 :)
    • 如果这个答案对您有帮助,那么您可以接受并投票,以便帮助其他有类似问题的人。 :)
    • 如果你想要 50% 50% 的孩子宽度,那么你可以给 flex-grow:1 给 flex child
    【解决方案2】:

    在带有类行的 div 上添加样式 display: flex;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-29
      • 2016-10-22
      • 2018-04-28
      • 2011-02-04
      • 1970-01-01
      • 1970-01-01
      • 2011-11-28
      • 2021-12-09
      相关资源
      最近更新 更多