skip to Main Content

There are many discussions about why height:100% doesn’t work when parent div has no set height.But this time I found it weirdly does work with the below codes and i don’t know why.

I don’t set the height value to the parent box, so the height:100% should not work for the child box, but it does work, and the height value is 48px.

<div style="
      display: flex;
      flex-direction: column;
      height: 200px;
      width: 200px;
      background-color: yellow;
    ">
  <div class="parent" style="background-color: black">
    <div class="child" style="height: 100%; width: 100%; background-color: blue">
      <span style="line-height:24px">123</span>
    </div>
    <div class="child" style="height: 100%; width: 100%; background-color: red">
      <span style="line-height:24px">123</span>
    </div>
  </div>
</div>
  • When I remove the span element, the child box has no child element, the height:100% is really not work.
  • When I remove the height:100%, the height value is 24px,same as line-height which I think is correct.
  • So why does this happen?

2

Answers


  1. The key takeaway here is the interaction between Flexbox and content-based sizing. In your example, the height of the .child divs is determined by the height of their content (the span elements), and this height is used to calculate the height of the .parent div. The height: 100% works because the parent’s height is derived from its children’s content, creating a feedback loop that gives the appearance of the height: 100% working as expected.

    Login or Signup to reply.
  2. Try it a little different and you can find out what is happening,
    each div is taking the 100% of full parent effective content.

    enter image description here

        <div style="display: flex; flex-direction: column; height: 200px; width: 200px; background-color: yellow; justify-content: center;">
          <div class="parent" style="width: 90%; background-color: black">
            <div class="child" style="height: 100%; width: 90%; background-color: blue">
              <span style="line-height:24px">123</span>
            </div>
            <div class="child" style="height: 100%; width: 90%; background-color: red">
              <span style="line-height:24px">123</span>
            </div>
          </div>
        </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search