Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does taking a percentage of body height result in 0 [duplicate]

Tags:

html

css

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?

like image 273
Black Wind Avatar asked Oct 22 '25 00:10

Black Wind


1 Answers

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.

like image 197
loomy Avatar answered Oct 24 '25 14:10

loomy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!