html - 让 div 使用最高 child 的高度

标签 html css css-float css-position

我有许多不同高度的 div,我想一次显示一个(用 visibility: hidden 隐藏其他的),但同时要确保内容div 下方保持原位。

我有这个小的 html 片段:

<html>
  <body>
    <div class="container">
      <div class="big box" >Big</div>
      <div class="small box">Small</div>
    </div>
    <div class="footer">Footer</div>
  </body>
</html>

使用这种样式:

.container {
  overflow-y: hidden;
}

.box {
  display: inline-block;
  width: 100px;
  position: absolute;
}

.big {
  height: 100px;
  visibility: inherit;
  background-color: lightgreen;
}

.small {
  height: 40px;
  background-color: lightblue;
}

.footer {
  width: 200px;
  background-color: pink;
}

我期望的是这样的:

+------------+
| Small      |  <-- The text "Big" is hidden by the small
|            |      box because it is rendered behind it.
+------------+
|            |
|            |
+------------+---------+
| Footer               |
+----------------------+

我知道当我使用 position: absolute 时,它不会工作,因为 container div 无法获得正确的高度,但是那又怎样呢?

这里的 JSBIN:http://jsbin.com/xakedogihi/7/edit?html,css,output

最佳答案

您可以使用 display:flexorder 来交换 div 的顺序:

.container {
  display:flex;
}

.box {
  order:1;
  width: 100px;
}

.big {
  order:2;
  height: 100px;
  visibility: hidden;
  background-color: lightgreen;
}

.small {
  height: 40px;
  background-color: lightblue;
}

.footer {
  width: 200px;
  background-color: pink;
}
<div class="container">
  <div class="big box">Big</div>
  <div class="small box">Small</div>
</div>
<div class="footer">Footer</div>

这应该适用于所有现代浏览器

更新

我想我明白你的意思了——两个 div 应该在不使用绝对定位的情况下彼此重叠,这样页脚就会保持在最高内容的下方。

.container {
  padding-left: 100px;
  /*width of inner boxes*/
  width: 0;
}
.container:after {
  content: '';
  display: block;
  height: 0;
  clear: both;
}
.container .box {
  margin-left: -100px;
  /*minus amount of padding above*/
  width: 100px;
}
.container .big {
  float: left;
  background: red;
}
.container .small {
  float: right;
  background: green;
}
.footer {
  background: blue;
}
<div class="container">
  <div class="big box">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc et facilisis sapien</div>
  <div class="small box">Small</div>
</div>
<div class="footer">Footer</div>

关于html - 让 div 使用最高 child 的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35988655/

相关文章:

javascript - 如何将具有相同 CLASS 的元素的父 ID 存储在数组中,并在警报中显示这些存储的 ID

html - 水平导航栏在 IE 和 Firefox 中不起作用

jquery - 在点击位置移动 map 上的角色

css - 如何在包装器的全高处 float 一个元素?

css - div 出现在 | 之前元素

html - float 的 div 与父级的高度不同

php - MySql分页; "Showing result-set"帮助的 "total found"

jquery - 使用下拉选项将文本放入 div

html - 为什么图像在 Foundation 6.4 Cards Component 中被拉伸(stretch)

html - 可以在 html 电子邮件上速记 CSS 吗?