Reputation: 12276
I have this simplified code:
This is a line of text<br/>
<div style="background-color: orange; height: 100%">And this is a div</div>
The div height ends up being 100% of the height of the browser window client space, which summed up with the height of the text line, is more than the window height, so you have to scroll.
How can I make the div height so it takes the height of the browser window minus the line of text?
Or, in other words, how can I make the div take all the free space vertically regarding what other DOM objects already occupy?
Upvotes: 10
Views: 20533
Reputation: 706
This can be done quite elegantly using display: table;
without needing to know any explicit height values.
Demo here: http://codepen.io/shanomurphy/pen/jbPMLX
html, body {
height: 100%; // required to make .layout 100% height
}
.layout {
display: table;
width: 100%;
height: 100%;
}
.layout__row {
display: table-row;
}
.layout__cell {
display: table-cell;
vertical-align: middle;
}
.layout__cell--last {
height: 100%; // force fill remaining vertical space
}
<div class="layout">
<div class="layout__row">
<div class="layout__cell">
Row 1 content
</div>
</div>
<div class="layout__row">
<div class="layout__cell layout__cell--last">
Row 2 fills remaining vertical space.
</div>
</div>
</div>
Upvotes: 0
Reputation: 416
I met the same problem too. Here is the solution I found:
<style>
.container{
position: relative;
height: 100%;
}
.top-div{
/* height can be here. if you want it*/
}
.content{
position:absolute;
left: 0;
right: 0;
bottom: 0;
top: 1em; /* or whatever height of upper div*/
background: red;
}
</style>
<div class="container">
<div class="top-div">This is a line of text</div>
<div class="content">And this is a div</div>
</div>
source - http://www.codingforums.com/archive/index.php/t-142757.html
Upvotes: 6
Reputation: 15867
Ultimately, you will want to have a container. "overflow: hidden" will hide anything that overflows the container. If we didn't use that then we would see the problem you mentioned above about "...is more than the window height, so you have to scroll".
<div id="container" style="color:white;height:500px;background-color:black;overflow:hidden;">
This is the container
<div style="height:100%;background-color:orange;">
This div should take the rest of the height (of the container).
</div>
</div>
Example with overflow hidden: http://jsbin.com/oxico5
Example without overflow hidden: http://jsbin.com/otaru5/2
Upvotes: 5