Let me show you the code first before explaining my issue:
Tinkerbin:
<style>
div.container{
height: 200px;
width: 200px;
background-color:red;
margin-top: 10px;
}
div.subContainer{
position: relative;
text-align: center;
}
div.inner{
position: absolute;
background-color:yellow;
width: 150px;
}
</style>
<div class="container">
<div class="subContainer">
<div class="inner">bananas for breakfast</div>
</div>
</div>
As per the textbook, when text-align: center;
is applied to a parent element, it only centers its child elements if they have display: inline;
.
Hence, since a <div>
by default has display set to block (display:block;
), the text-align: center;
on the parent div.subContainer
does not affect its child div.inner
.
Everything seems fine until now. No surprises yet.
The problem arises when I replace <div>
with <span>
in the .inner
element and position it absolutely (position: absolute;
) - which changes its display from inline to block as you are aware.
Have a look:
<style>
div.container{
height: 200px;
width: 200px;
background-color:red;
margin-top: 10px;
}
div.subContainer{
position: relative;
text-align: center;
}
span.inner{
position: absolute;
background-color:yellow;
width: 150px;
}
</style>
<div class="container">
<div class="subContainer">
<span class="inner">bananas for breakfast</span>
</div>
</div>
The outcome is unexpected. Despite having the display value forced to block (due to position: absolute;
), the span is still centered. Moreover, the alignment is peculiar. It aligns the left side of the block with the center of the containing element instead of centering both sides.
This behavior is rectified - starts acting like a block - when I manually set the display on span.inner
to block.
span.inner{
position: absolute;
display: block;
background-color:yellow;
width: 150px;
}
So, what's causing this confusion? Shouldn't absolute positioning force a change in display to block? Why is the centering behaving strangely?