有一个div来填充容器的剩余高度/宽度与另一个div共享?

时间:2013-08-30 17:35:37

标签: html css

说我有以下设置:

<div class="A parent">
    <div class="A a1"></div>
    <div class="A a2"></div>
    <div class="A a3"></div>
</div>

CSS:

.A {
    width: 100%;
}

.parent {
    height: 300px;
    width: 300px
}

.a1 {
    height: 100px;
 }

.a2 {
    height: 100px;
}

.a3 {
    // ??
}

有什么方法可以让.a3填写父div的剩余高度,没有任何内容,没有明确说明它的高度?这对响应式设计非常有用。

4 个答案:

答案 0 :(得分:2)

在这种情况下,由于您的父容器具有硬编码高度,因此您可以将.a3的高度设置为100%:

<强> CSS

.parent {
  overflow: hidden; /** This will hide the overflow **/
  height: 300px;
  width: 300px
}

.a3 {
  background: blue;
  height: 100%;
}

Codepen example.

使用Flexbox解决方案更新

使用flexbox并定义flex-direction column,您可以让您的列根据父容器有机地采用高度。

<强> CSS

.parent {
  display: flex; /** Set display type **/
  flex-direction: column; /** Flexbox direction **/
  flex-wrap: nowrap; /** Each row should take up 100% of the width **/
  height: 300px;
  width: 300px;
}


.a1, .a2, .a3 {
  flex-grow: 1; /** 1 per row **/
}

.a1 { background: green; } /** No more explicit heights, if you want **/
.a2 { background: red; }
.a3 { background: blue; }

答案 1 :(得分:2)

这是一种简单的方法。由于您知道父级和前两个子元素的高度,因此可以对第三个子块使用绝对定位:

.A {
    width: 100%;
}
.parent {
    height: 300px;
    width: 300px;
    position: relative;
}
.a1 {
    height: 100px;
    background-color: pink;
}
.a2 {
    height: 100px;
    background-color: beige;
}
.a3 {
    background-color: yellow;
    position: absolute;
    top: 200px;
    bottom: 0;
}

请参阅演示:http://jsfiddle.net/audetwebdesign/WbRZn/

这使用CSS2,因此它应该向后兼容,可能回到IE5。

答案 2 :(得分:1)

根据您的目标,您可以始终使用.a3打开前两个框,然后在height: 100%上设置a3

答案 3 :(得分:0)

以防OP对@ kunalbhat的回答的第一个评论是一个重要的要求

  

如果其中一个元素(比如中间元素)没有明确的高度,那该怎么办呢?   从内容中获得高度?

您可以像这样使用display: table;display: table-row;

<强> CSS:

.A {
    width: 100%;
}
.parent {
    height: 200px;
    width: 300px;
    position: relative;
    display: table;
}
.a1 {
    background-color: pink;
}
.a2 {
    background-color: beige;
}
.a3 {
    background-color: yellow;
    height: 100%;
    display: table-row;
}

这是一个 jsFiddle ,这应该是work in and IE8+ and all other browsers