text-align:center Not working properly on absolute positioned spans

Ali Bassam picture Ali Bassam · Feb 26, 2013 · Viewed 14.7k times · Source

I need to place 2 <span> inside a <div>, the first span must be placed on top, the second one on bottom, like North-South.

enter image description here

<div>
    <span class="north">N</span>
    <span class="south">S</span>
</div>

To do this, I thought about using position:absolute; on the 2 <span>.

div
{
    display:inline-block;
    width: 20px;
    position:relative;
    height:100px;
}
.north
{
    position:absolute;
    top:0;
}
.south
{
    position:absolute;
    bottom:0;
}

Now, the spans should be positioned to the left (default), to center them, I used:

div
{
    text-align:center;
}

But I got this:

enter image description here

Check it out : http://jsfiddle.net/Zn4vB/

Why is this Happening?

Note: I cannot use margins, left, right, because the contents of those spans are different, I just need to align them properly in the center.

Answer

Eli Gassert picture Eli Gassert · Feb 26, 2013

http://jsfiddle.net/Zn4vB/1/

The issue is that once absolutely positioned, it no longer follows the document flow. So the text is centered, but only inside the pink span. And since it's absolutely positioned, even if it were a div, the width would collapse.

The solution is to give the positioned spans a 100% width and then centering works.

span
{
    background-color:pink;
    left: 0;
    width: 100%;
}

If you don't want the pink to extend the full width, then you must nest an element (e.g. span) inside the positioned spans and give that element the background color, as seen here: http://jsfiddle.net/Zn4vB/6/