如何实现三个同行div自适应内容高度且保持高度一致?

有三个div居中于页面,每一个结构如下。

<div>
    <img>
    <p>
<div>

纯css方案。

最后采用了 @dolymood 的方法,感谢各位的回答。

总结:

  • @dolymood 的方法:为父元素设置 overflow:hidden。再为子元素设置大的 padding-bottom 属性,再用稍大一点的 margin-bottom 属性抵消;

  • @pantao @MockingBird 的方法采用了table布局,父元素 display:table,子元素 display:table-ceil

阅读 36.8k
6 个回答

父级元素overflow:hidden
里边的三个子元素 每一个都是设置一个大的padding-bottom 然后用margin-bottom抵消掉就可以了

关键点:display:table

直接将下面的代码粘贴至一个 html 文件即可,图片如果打开慢的话,可以换成本地的即可。

html<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
  <title>等高布局</title>
  <style>
    html {
      font-size: 10px;;
    }
    body {
      font-size: 1.4rem;
    }
    .box {
      background-color: rgba(200,200,200,0.7);
      margin: 0 1rem;
      width: 33.33%;
      padding: 1rem;
    }
    .box:nth-child(2) {
      height: 5rem;
      background-color: rgba(200,210,230,0.7);
    }
    .accordant {
      display: table-row;
    }
    .table {
      width: 100%;
      display: table;
    }
    .table .accordant {
      display: table-row;
    }
    .table .accordant .box {
      display: table-cell;
      vertical-align: middle;
      text-align: center;
    }
  </style>
</head>
<body>
<div class="table">
  <div class="accordant">
    <div class="box">
      <img src="http://placehold.it/200x200.png" alt="200x200"/>
      <p>这是一个 Figure</p>
    </div>
    <div class="box">
      <img src="http://placehold.it/250x250.png" alt="200x200"/>
      <p>这是一个 Figure</p>
    </div>
    <div class="box">
      <img src="http://placehold.it/300x300.png" alt="200x200"/>
      <p>这是一个 Figure</p>
    </div>
  </div>
</div>
</body>
</html>

对每个 div 的高度不进行限制,即:

height:auto;

同时,写 js 脚本,获取三个 div 的高度,取三个 div 中高度值最大的那个,然后再将其他两个高度较小的 div 的 height 赋值为三个 div 中最大的高度值。

题主是指三个div的高度一样,都等于内容最高的那个div的高度吗?

<div class="container">
    <div class="item bg1">哈哈哈</div>
    <div class="item bg2">方法发发士大夫</div>
    <div class="item bg3">fasdfffffffffffffffffffffffffffas</div>
</div>
.container{
    width: 330px;
    display: flex;
    justify-content: space-between;
    align-items: stretch;
}
 .item{
   width: 50px;
   height: auto;
   word-wrap:break-word;
 }
.bg1{
  background: red;
}
.bg2{
  background: green;
}
.bg3{
  background: blue;
}

image.png

推荐问题