In css the position properties seem simple but in reality, there‘s tons of weird edge cases that seemingly come out of nowhere when building a layout.
One thing that I always skimmed over was when I would see height: auto
or width: auto
. In trying to understand this better, I came across the below code and I am hoping someone can try to explain why this happens.
The reason I am confused is if position: absolute
is used, since height
and width
are both auto
on the parent, the parent becomes 50px
x 50px
.
This doesn't happen though when the parent is relatively positioned. When the parent has position: relative
, height: auto
works but width: auto
does not cause the parent to take on the width of it‘s child as I would expect. Instead with position: relative
, the element stretches the length of the whole line.
body {
margin: 0;
padding: 0;
}
.a {
/*
why is width auto not respected, but height auto takes the
height of the child??
if position was absolute then the height and width
both take on the dimensions of the child
*/
position: relative;
background: #ff9999;
top: 10px;
height: auto;
width: auto;
}
.b {
position: relative;
background: blue;
top: 10px;
height: 50px;
width: 50px;
}
<div >
<div ></div>
</div>
CodePudding user response:
It's not only related to position but also to the display of the element. You can find how the width of each element is calculated here https://www.w3.org/TR/CSS22/visudet.html#Computing_widths_and_margins
You will see a lot of categories. When your element is position: relative
we don't care about position but we see other criteria like the fact it's a block level element and it follows the rule:
'margin-left' 'border-left-width' 'padding-left' 'width' 'padding-right' 'border-right-width' 'margin-right' = width of containing block
And when it's position: absolute
we consider different rules and somewhere you can read:
.. then the width is shrink-to-fit
I won't detail each case but you can read the first link to understand all the cases of width calculation. They are a lot but a quick reading will give you a clear idea on how the width and height of the elements is calculated.