HTML 5/CSS Percent Height Tips
P粉135292805
2023-08-20 19:15:25
<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>
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: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 haveheight: 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
):View hereMore information.