3

So I thought I can't set height in % if the parent doesn't have set height even if one of the children have a static height and is stretching the parent, but now I realized that if the child is position absolute it can. Why can a position absolute child have % height, but a block, inline or float child can't? http://jsfiddle.net/4vmeqf16/

body > div{
  background: black;
  
}
div div:nth-child(1){
  width: 50px;
  height: 50px;
  background: red;
}
div div:nth-child(2){
  width: 20%;
  height: 20%;
  background: green;
}
div div:nth-child(3){
  width: 20%;
  height: 20%;
  position: absolute;
  background: yellow;
}
<div>
  <div></div>  
  <div></div>
  <div></div>
</div>

1 Answers1

3

Because a position:absolute element has no effect on the height of its containing block. So there's no height circular dependency unlike your other cases. The containing block can be laid out using its in-flow children, its height determined, and only then need the absolute positioned element be laid out.

Alohci
  • 78,296
  • 16
  • 112
  • 156
  • I guess it makes sense, because if the child is set to 120% height it must also stretch the parent and it becomes infinite stretching between the child and the parent. But is it design decision couldn't the height of the block child just have max of 100% and no more? –  May 29 '21 at 22:18
  • @heyza22 - I know what you mean. There are cases where a parent and a sole child could have a determinate heights if the parent had a min-height and the child's outer edge height summed to less than 100% of that min-height. But that's a pretty special case. It breaks down in all kinds of cases. There's a second child, the margins, paddings and borders extend the outer edges to more than 100% height, and so on. CSS 2, in particular, just doesn't allow for any opportunities for circular dependencies. – Alohci May 29 '21 at 22:38
  • 1
    @heyza22 there are even more complex cases where we can resolve percentage without absolute (related: https://stackoverflow.com/a/56701229/8620333 / https://stackoverflow.com/a/65116080/8620333) – Temani Afif May 29 '21 at 22:56
  • @TemaniAfif Thanks I will definitely look it up. –  May 29 '21 at 23:01