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
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.
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