search

Home  >  Q&A  >  body text

HTML 5/CSS Percent Height Tips

<p>I'm trying to set a <div> to a specific percentage height in CSS, but it's still the same size as the content within it. However, when I remove HTML 5's <!DOCTYTPE html>, it works fine and the <div> takes up the entire page as expected. I want the page to pass verification, what should I do? </p> <p>I have this CSS on <div> and its ID is <code>page</code>: </p> <pre class="brush:php;toolbar:false;">#page { padding: 10px; background-color: white; height: 90% !important; }</pre>
P粉135292805P粉135292805460 days ago607

reply all(2)I'll reply

  • P粉759451255

    P粉7594512552023-08-21 18:49:34

    You also need to set the height on the <html> and <body> elements; otherwise, they will only be large enough to fit the content. For example:

    <!DOCTYPE html>
    <title>Example of 100% width and height</title>
    <style>
    html, body { height: 100%; margin: 0; }
    div { height: 100%; width: 100%; background: red; }
    </style>
    <div></div>

    reply
    0
  • P粉530519234

    P粉5305192342023-08-21 00:27:22

    What is the percentage?

    To set the percentage height, its parent element (*) must have an explicit height. This is fairly obvious, if you leave the height as auto, the block will take the height of its content... However, if the height of the content itself is expressed as a percentage of the parent element, you're stuck in a Little dilemma. The browser gives up and just uses the content height.

    Therefore, the parent element of the div must have an explicit height attribute. While the height can be a percentage if you prefer, that just takes the problem to the next level.

    If you want the height of a div to be a percentage of the viewport height, then every ancestor element of the div, including <html> and <body>, Must have height: 100%, so there is an explicit percentage height chained to the div.

    (*: Or, if the div is positioned, the "containing block", the nearest ancestor element that is also positioned.)

    Alternatively, all modern browsers and IE>=9 support new CSS units relative to viewport height (vh) and viewport width (vw):

    div {
        height:100vh; 
    }

    View hereMore information.

    reply
    0
  • Cancelreply