简体   繁体   中英

Have a div to fill out the remaining height/width of a container when sharing it with another div?

Say I've got the following setup:

<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 {
    // ??
}

Is there any way I can get .a3 to fill out the remaining height of the parent div, without any content and without explicitly stating its height? This would be so useful for responsive design.

In this case, since you have a hardcoded height to your parent container, you can set the height of .a3 to 100%:

CSS

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

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

Codepen example.

UPDATE with Flexbox solution

Using flexbox , and defining a flex-direction of column , you can have your columns organically assume a height based on a parent container.

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; }

Here is a simple way of doing it. Since you know your heights of the parent and the first two child elements, you can use absolute positioning for the third child block:

.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;
}

See demo: http://jsfiddle.net/audetwebdesign/WbRZn/

This uses CSS2 so it should be backwards compatible, probably back to IE5.

根据要使用的外观,始终可以使用.a3包裹前两个框,然后设置height: 100%a3上设置height: 100%

Just in case OP's first comment on @kunalbhat's answer is an important requirement

What if one of the elements, say the middle one, has no explicit height but gets its height from its content?

you can use display: table; and display: table-row; like this:

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;
}

Here's a jsFiddle , this should work in and IE8+ and all other browsers .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM