MacMac
MacMac

Reputation: 35341

Horizontally center an absoluted element without fixed width

I'm trying to make an absolute element align in the middle without a fixed width, this is I've tried:

.rm-line {
    background-color: #CCC;
    height: 4px;
    position: relative;
    text-align: center;
}

.rm-line span {
    position: absolute;
    background-color: #FFF;
    padding: 0 10px;
    top: -4px;  
}

Demo at jsFiddle. As you can see in the demo, the text is not centered, I need this to be centered at any text width, even if the text has more or less characters, it should align in the middle.

How can I achieve this?

Upvotes: 2

Views: 2248

Answers (3)

lumbric
lumbric

Reputation: 9093

I don't know why, but in Firefox it seems to work as desired if you set the span-box position to relative:

.rm-line span {
    position: relative;
    background-color: #FFF;
    padding: 0 10px;
    top: -4px;
}

Upvotes: 0

thirtydot
thirtydot

Reputation: 228222

Assuming that using relative/absolute positioning isn't a requirement..

You should use display: inline-block on your span instead of position: absolute. The span will be centered by text-align: center on the div.

See: http://jsfiddle.net/2WNPm/12/

Upvotes: 3

kleinohad
kleinohad

Reputation: 5912

 .rm-line span {

     background-color: #FFF;
     padding: 0 10px;
     top: -4px;    
    margin:auto;
    display:block;
 }

Upvotes: 0

Related Questions