Consider the following HTML/css code sample:
<div id="container">
<div id="up">Text<br />Text<br />Text<br /></div>
<div id="down">Text<br />Text<br />Text<br /></div>
</div>
#container { width: 300px; height: 300px; border:1px solid red;}
#up { background: green; }
#down { background:pink;}
where I have a container div with two children (also here: http://jsfiddle.net/S8g4E/). The first child has a given height. How can I make the second child to occupy the "free space" of the container div without giving a specific height?
In the example, the pink div should occupy also the white space.
Similar to this question: How to make div occupy remaining height?
But I don’t want to give position absolute.
Expanding the
#downchild to fill the remaining space of#containercan be accomplished in various ways depending on the browser support you wish to achieve and whether or not#uphas a defined height.Note (2024): CSS now has
max-contentproperty value for sizing as well, so if you don’t have a fixed height (e.g. 100px) then you might be able to use that.Samples
Grid
CSS’s
gridlayout offers yet another option, though it may not be as straightforward as the Flexbox model. However, it only requires styling the container element:The
grid-template-rowsdefines the first row as a fixed 100px height, and the remain rows will automatically stretch to fill the remaining space.I’m pretty sure IE11 requires
-ms-prefixes, so make sure to validate the functionality in the browsers you wish to support.Flexbox
CSS3’s Flexible Box Layout Module (
flexbox) is now well-supported and can be very easy to implement. Because it is flexible, it even works when#updoes not have a defined height.It’s important to note that IE10 & IE11 support for some flexbox properties can be buggy, and IE9 or below has no support at all.
Calculated Height
Another easy solution is to use the CSS3
calcfunctional unit, as Alvaro points out in his answer, but it requires the height of the first child to be a known value:It is pretty widely supported, with the only notable exceptions being <= IE8 or Safari 5 (no support) and IE9 (partial support). Some other issues include using calc in conjunction with transform or box-shadow, so be sure to test in multiple browsers if that is of concern to you.
Other Alternatives
If older support is needed, you could add
height:100%;to#downwill make the pink div full height, with one caveat. It will cause overflow for the container, because#upis pushing it down.Therefore, you could add
overflow: hidden;to the container to fix that.Alternatively, if the height of
#upis fixed, you could position it absolutely within the container, and add a padding-top to#down.And, yet another option would be to use a table display: