I was going through this doc about containing blocks. Note the Example 2 here.
HTML:
<body>
<section>
<p>This is a paragraph!</p>
</section>
</body>
CSS:
body {
background: beige;
}
section {
display: inline;
background: lightgray;
}
p {
width: 50%; /* == half the body's width */
height: 200px; /* Note: a percentage would be 0 */
background: cyan;
}
In the CSS inline comment, it states that a percentage would be 0. Why is this the case?
My understanding has been that a block element's height would be the height of its content unless explicitly set. Can someone clarify why a percentage of the height would be zero and also, if my understanding is wrong?
In CSS, percentage-based sizes are relative to the parent of the element. The parent must also have a fixed (read: non-percentage) size.
In this case, body has no defined height, and so you get this:
body {
background: beige;
}
section {
display: inline;
background: lightgray;
}
p {
width: 50%;
height: 100%;
background: cyan;
}
<body>
<section>
<p></p>
</section>
</body>
You can test this by giving body or section a fixed size and seeing the result:
body {
background: beige;
height: 250px;
}
section {
display: inline;
background: lightgray;
}
p {
width: 50%;
height: 100%;
background: cyan;
}
<body>
<section>
<p></p>
</section>
</body>
The cyan box now takes up 100% of the value of the height of body.
One of the workarounds that you will often see used for this scenario is that people will give the top-level container a size relative to the viewport. If we give body, say, height: 50vh, and then give p a height of 100%, even though viewport height is a scalar/percentage based unit, it will resolve as you would desire.
body {
background: beige;
height: 50vh;
}
section {
display: inline;
background: lightgray;
}
p {
width: 50%;
height: 100%;
background: cyan;
}
<body>
<section>
<p></p>
</section>
</body>
However, because you have content inside of your <p> element, a percentage-based height would not resolve to zero. I believe the comment in the original example was made to illustrate the fact that a percentage-based height would not increase the height beyond the native size of the <p> and its contents, but could have been phrased slightly better to say something along these lines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With