简体   繁体   中英

CSS height not working if body has min-height

I don't get my first child in the body to 100% height, if the body has min-height specified.

<html>
    <head>
        <style>
            html {
                height:100%;
            }
            body {
                min-height:100%;
            }
            #wrapper {
                height:100%;
                min-width:1120px; /* 250px each side (content width is 870px) */
                max-width:2000px;
                background-image:url(bg.png);
                background-position:50% 25px;
                background-repeat:no-repeat;
                background-size:cover;
            }
        </style>
    </head>
    <body>
        <div id="wrapper">
            <!-- web content -->
        </div>
    </body>
</html>

This does not resize the wrapper to the height of the window. When I remove the min- and use height , it'll work. But I have to have the content height variable...

I did find some other posts here on SO and on google, but they have just questions and no solution.

When you use a percentage value for height , it will always be relative to the specified height of the parent element. Not the actual height of the parent element, but the height specified in CSS.

So when your body element has no height specified (only min-height , but that does not count), the 100% will not be able to take effect.

One possible solution is to use position: absolute; top: 0; bottom: 0; position: absolute; top: 0; bottom: 0; on your #wrapper , and your div will be stretched. This of course might have some layout consequences that you do not want.

jsFiddle Demo

Short Answer

Use height:100vh; for divs you want to stretch and fill the screen.

Do not set body's height: 100%; It will break your entire site if you have pages that have more than 100% in content height. They won't be able to scroll.

Long Answer

If you want a few pages of your website to fill the entire screen while still allowing other pages to scroll (because they have more than 100% height in content), you need to set the div height to 100%, not the entire site-wide body height.

Use this as general site-wide css:

html {
    height: 100%;
}

body {
    min-height: 100%;
}

Then set specific divs to fill the entire screen (when they have less than 100% height in content):

/* Set any div heights to 100% of the screen height*/
.div {
    height:100vh;
}

Explanation of the vh measurement: https://stackoverflow.com/a/16837667/4975772

I actually found a solution!

Now I have:

html, body {
    height:100%;
}

So my body is not min-height . I don't remember why I changed it to min-height , but I hope I won't face the issue I obviously faced some time ago...

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