简体   繁体   中英

How to make a DIV take up the remainder of the page?

I have the following HTML:

<html>
<body>
  <h2>Title</h2>
  <div id='large_div'>
    blah.. blah.. blah..
  </div>
</body>
</html>

How can I make the large_div take up the rest of the page height?

Here is the CSS for the page:

html { height: 100%; }
body { height: 100%; }
#large_div {
    /* ??? */
}

You could try setting a negative margin on the #large_div that was equal to the height of the h2. Unfortunately this will not very solid code since that h2 height will change depending on text length and browser:

#large_div {
    height: 100%;
    margin-top: -1em; /* adjust to height of h2 */
}

A bit of jQuery would sort you out though:

$(document).ready(function(){
    $('#large_div').css({height: $(window).height() - $('h2').height()});
});

So, you basically want a table layout? This is one of the nastiest things in CSS. You might consider to fall back to old fashioned HTML tables, but if you don't care about IE6/7 support , then you can also play around using display attributes of table , table-row and eventually table-cell .

Here's an SSCCE, copy'n'paste'n'run it.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 3323454</title>
        <style>
            html { 
                height: 100%;
            }
            body { 
                display: table; 
                margin: 0;
                width: 100%;
                height: 100%;
            }
            #large_div {
                display: table-row; 
                width: 100%;
                height: 100%;
                background: pink;
            }
        </style>
    </head>
    <body>
        <h2>Title</h2>
        <div id="large_div">blah.. blah.. blah..</div>
    </body>
</html>

Again, this works in decent CSS2-adhering browsers only.

If all you want to achieve is to give the div a nice background, then there are nicer solutions.

html,body {height:100%;border:0px;margin:0px;padding:0px;}

#large_div {height:100%;margin:0px;}

If you knew the height of the top div (or h2 in this case), you might be able to try something like the following:

#topdiv { height:100px; }
#bottomdiv { height:100%; margin-bottom:-100px; bottom:0; }

Unfortunately, I can't test this from where I am right now, so this could be way off... But I believe I've used something similar to this before and it had a similar effect.

You may be able to find your solution - or at least a "good enough" solution, by playing around with those css properties...

Good luck!

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