Although CSS position properties may seem simple at first, when building a layout, tons of weird edge cases can come out of nowhere.
One thing that I always overlooked was using height: auto
or width: auto
. To gain a better understanding, I stumbled upon the code below and now I'm hoping someone can explain why this phenomenon occurs.
I'm puzzled because when position: absolute
is used and both height
and width
are set to auto
on the parent element, the parent ends up being 50px
x 50px
.
However, this behavior does not occur when the parent is relatively positioned. In such case, even though height: auto
works fine, setting width: auto
does not cause the parent to match the width of its child as expected. Instead, with position: relative
, the element extends along the entire line.
body {
margin: 0;
padding: 0;
}
.a {
/*
Why is 'width:auto' not respected while 'height:auto' takes the height of the child??
If 'position' were set to 'absolute', then both 'height' and 'width'
would take on the dimensions of the child element
*/
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>