HTML/CSS: stretching height <div> layout

1.7k views Asked by At
<div style="width: 800px; height: 600px"> 
    <div style="height: 100px"> 
        top fixed-height row
    </div> 
    <div style="???"> 
        bottom stretching row (the height should be 500px in this case.) 
    </div> 
</div> 

What's the standard way to create two-row layout without javascript where the top one is fixed-size and the bottom one stretches and fits to its parent div?

  • I would like both rows' styles are independent. I found a couple of solutions here, but if I change the height of the top row, the bottom row's style (e.g. margin) need to be changed along with it.

  • I don't need to support old browsers. If it's standard, it's just okay.

Thanks!

4

There are 4 answers

2
Bongs On BEST ANSWER

You can use display property in CSS to fix this.

working EXAMPLE

HTML

<div id="a" style="width: 300px; height: 200px"> 
    <div id="b" style="height: 55%"> 
        top fixed-height row
    </div> 
    <div id="c" style=""> 
        bottom stretching row (the height should be 500px in this case.) 
    </div> 
</div> ​

CSS

#a
{
    border: 1px solid black;
    display:table;
}
#b
{
    background-color:red;
    display:table-row;
}
#c
{
    background-color:green;
    display:table-row;
}​
1
FluffyKitten On

HTML and CSS are static not dynamic languages where you could perform calculations. You can only apply styles to each div individually because there is actually no dependency between the styles for each "row" div for you to determine the height of one based on the other.

However depending on what you are trying to achieve, it may be possible to style the containing div instead of the bottom div.

e.g. a very simplistic example where the top row should have a red background and bottom row have a yellow background, set the style for the containing div to have the appearance you require for the bottom div, and the top div will cover this appearance on the upper part of the container:

div#containingdiv { width: 800px; height: 600px; background:#ffff00; }
div#toprow { height: 100px; background:#ff0000; width 100%; }
div#bottomrow { }
0
mborecki On

For this case you can use preprocesor (like LESS):

@contHeight: 600px;
@topHeight: 100px;

div#containingdiv { 
    width: 800px; 
    height: @contHeight; 
    }
div#toprow { 
    width: 100%;
    height: @topHeight; 
    }
div#bottomrow {
    height: @contHeight - @topHeight; 
    }
0
MadManMathew On

I have just written a blog about HTML CSS layouts, the demo lets you manipulate most css settings via javascript.

http://attemptingawesomeness.blogspot.com.au/2012/05/css-html-layout-guide_13.html

http://attemptingawesomeness.blogspot.com.au/2012/05/ultimate-html-css-layout-demo.html