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 class="a">
<div class="b"></div>
</div>
>Solution :
The behavior you are seeing with the height: auto and width: auto properties is due to the way that the CSS layout engine calculates the dimensions of elements.
When an element has a position value of absolute, its dimensions are calculated based on its content, regardless of whether height or width are set to auto. This means that if an element with position: absolute has a child element with fixed dimensions, the parent element will take on those dimensions as well.
On the other hand, when an element has a position value of relative, its dimensions are calculated differently. If an element has a width value of auto, the element will stretch to fill the available space in the parent element. If an element has a height value of auto, the element will take on the height of its content, as you observed.
In your example, the .a element has a position value of relative and both height and width are set to auto. This causes the .a element to stretch to the full width of the parent element (in this case, the viewport) and take on the height of its content, which is the .b element. The .b element, on the other hand, has fixed dimensions of 50px x 50px, so it does not stretch to fill the parent element.
I hope this helps to clear up the behavior you are seeing with height: auto and width: auto.