Make body have 100% of the browser height

后端 未结 21 1385
离开以前
离开以前 2020-11-22 00:26

I want to make body have 100% of the browser height. Can I do that using CSS?

I tried setting height: 100%, but it doesn\'t work.

I want to set

21条回答
  •  后悔当初
    2020-11-22 00:31

    What I use on the start of literally every CSS file I use is the following:

    html, body{
        margin: 0;
    
        padding: 0;
    
        min-width: 100%;
        width: 100%;
        max-width: 100%;
    
        min-height: 100%;
        height: 100%;
        max-height: 100%;
    }
    

    The margin of 0 ensures that the HTML and BODY elements aren't being auto-positioned by the browser to have some space to the left or right of them.

    The padding of 0 ensures that the HTML and BODY elements aren't automatically pushing everything inside them down or right because of browser defaults.

    The width and height variants are set to 100% to ensure that the browser doesn't resize them in anticipation of actually having an auto-set margin or padding, with min and max set just in case some weird, unexplainable stuff happens, though you probably dont need them.

    This solution also means that, like I did when I first started on HTML and CSS several years ago, you won't have to give your first

    a margin:-8px; to make it fit in the corner of the browser window.


    Before I posted, I looked at my other fullscreen CSS project and found that all I used there was just body{margin:0;} and nothing else, which has worked fine over the 2 years I've been working on it.

    Hope this detailed answer helps, and I feel your pain. In my eyes, it is dumb that browsers should set an invisible boundary on the left and sometimes top side of the body/html elements.

提交回复
热议问题