How can an html element fill out 100% of the remaining screen height, using css only?

后端 未结 17 1880
名媛妹妹
名媛妹妹 2020-12-22 16:13

I have a header element and a content element:

#header
#content

I want the header to be of fixed height and the content to fill up all the

17条回答
  •  抹茶落季
    2020-12-22 16:55

    Please let me add my 5 cents here and offer a classical solution:

    html {height:100%;}
    body {height:100%; margin:0;}
    #idOuter {position:relative; width:100%; height:100%;}
    #idHeader {position:absolute; left:0; right:0; border:solid 3px red;}
    #idContent {position:absolute; overflow-y:scroll; left:0; right:0; border:solid 3px green;}
    Header section
    Content section

    This will work in all browsers, no script, no flex. Open snippet in full page mode and resize browser: desired proportions are preserved even in fullscreen mode.

    Note:

    • Elements with different background color can actually cover each other. Here I used solid border to ensure that elements are placed correctly.
    • idHeader.height and idContent.top are adjusted to include border, and should have the same value if border is not used. Otherwise elements will pull out of the viewport, since calculated width does not include border, margin and/or padding.
    • left:0; right:0; can be replaced by width:100% for the same reason, if no border used.
    • Testing in separate page (not as a snippet) does not require any html/body adjustment.
    • In IE6 and earlier versions we must add padding-top and/or padding-bottom attributes to #idOuter element.

    To complete my answer, here is the footer layout:

    html {height:100%;}
    body {height:100%; margin:0;}
    #idOuter {position:relative; width:100%; height:100%;}
    #idContent {position:absolute; overflow-y:scroll; left:0; right:0; border:solid 3px green;}
    #idFooter {position:absolute; left:0; right:0; border:solid 3px blue;}
    Content section
    Footer section

    And here is the layout with both header and footer:

    html {height:100%;}
    body {height:100%; margin:0;}
    #idOuter {position:relative; width:100%; height:100%;}
    #idHeader {position:absolute; left:0; right:0; border:solid 3px red;}
    #idContent {position:absolute; overflow-y:scroll; left:0; right:0; border:solid 3px green;}
    #idFooter {position:absolute; left:0; right:0; border:solid 3px blue;}
    Header section
    Content section
    Footer section

提交回复
热议问题