Math chiller
Math chiller

Reputation: 4167

margin:auto; not adding a margin

im playing around with a loading bar in this fiddle, and i have this code

html

<div id="back"><span id="text">loading...</span></div>

css

#back {
    width:100px;
    background-color:#bbbbbb;
}

#text {
    z-index:2;
    height:30px;
    position: absolute;
    margin:auto;
}

div{
    height:30px;
    position: absolute;
}

yet the span does not have a margin, it looks like this

img

when i give it a normal margin value it works.

i have also tried margin: 0 auto; but also with no success. and when i try margin:10px auto; i get the 10px but not the auto.

Upvotes: 1

Views: 49

Answers (2)

meub
meub

Reputation: 2308

It's because the text is position absolute. Try this:

#back {
    width:100px;
    background-color:#bbbbbb;
    text-align:center;
}

#text {
    z-index:2;
    height:30px;
    line-height:30px;
    position: relative;
}

JSFiddle: http://jsfiddle.net/h6BRn/13/

Upvotes: 1

showdev
showdev

Reputation: 29168

Applying auto margin to an absolutely positioned inline element with unknown width introduces various problems.

I had success centering the text by setting line-height and text-align:center like so:

#text {
    position: absolute;
    z-index:2;
    width:100%;
    height:30px;
    line-height:30px;
    text-align:center;
}

http://jsfiddle.net/ruzED/

Upvotes: 1

Related Questions