首页 > 解决方案 > 如何设置浮动元素自动填充其父元素的剩余高度(高度不固定并显示为表格)?

问题描述

我有以下代码:

.parent {width: 960px; display: table}

.1 {
  width: 45%;
  margin: 20px;
  float: left;
  height: 1000px; /* it can be smaller or bigger than this value to fit its content */
}

.2 {
  width: 45%;
  margin: 20px;
  float: right;
  height: 200px;
}

.3 {
  width: 45%;
  margin: 20px;
  float: right;
}
<div class="parent">
  <div class="1">1</div>
  <div class="2">2</div>
  <div class="3">3</div>
</div>

我如何为“3”类编写 CSS,以便它的高度自动填充表格的剩余高度(在上面的例子中,720px,因为我假设父元素也有 1000px 的高度)?请注意,类“1”的高度可以根据其内容而改变。

题外话:除了我现在使用的代码(仅使用CSS和HTML)之外,有没有更好的方法让它看起来像下面的图片?

桌子的形象

标签: htmlcsshtml-tablecss-float

解决方案


试试这个。第三个元素(绿色)将根据高度进行调整.one。但它是基于.two具有固定尺寸的假设来实现的。

.parent {
    width: 960px;
    border: solid 2px #999;
    float: left;
    position: relative;
}
.one {
    width: 50%;
    float: left;
    height: 1000px;
    background: #ccc;
}
.two {
    width: 50%;
    float: right;
    height: 200px;
    background: #aaa;
}
.three {
    position: absolute;
    top: 200px;
    left: 50%;
    right: 0;
    bottom: 0;
    background: green;
}
<div class='parent'>
    <div class='one'>one</div>
    <div class='two'>two</div>
    <div class='three'>three</div>
</div>


推荐阅读