Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 690
Ali Bassam Avatar asked Feb 26 '13 18:02

Ali Bassam


2 Answers

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/

like image 115
Eli Gassert Avatar answered Oct 05 '22 22:10

Eli Gassert


please check if this one is the idea you want..

div
{
    display:inline-block;
    width: 20px;
    position:relative;
    height:100px;
    border-style:solid;
}
span
{
    background-color:pink;
    width:100%;
    text-align:center;
}
.north
{
    position:absolute;
    top:0;
}
.south
{
    position:absolute;
    bottom:0;
}
like image 24
nexus_07 Avatar answered Oct 05 '22 23:10

nexus_07