Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a layer with an image inside:

<div id="foo"><img src="url" /></div>

and it is fixed positioned:

#foo {
    position: fixed;
}

but I also want the layer to be horizontally centered in the page. So I've tried: http://jsfiddle.net/2BG9X/

#foo {
    position: fixed;
    margin: auto
}

and http://jsfiddle.net/2BG9X/1/

#foo {
    position: fixed;
    left: auto;
}

but doesn't work. Any idea of how to achieve it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
371 views
Welcome To Ask or Share your Answers For Others

1 Answer

When you position an element to fixed, it gets out of the document flow, where even margin: auto; won't work, if you want, nest an element inside that fixed positioned element and than use margin: auto; for that.

Demo

Demo 2 (Added height to the body element so that you can scroll to test)

HTML

<div class="fixed">
    <div class="center"></div>
</div>

CSS

.fixed {
    position: fixed;
    width: 100%;
    height: 40px;
    background: tomato;
}

.center {
    width: 300px;
    margin: auto;
    height: 40px;
    background: blue;
}

Some will suggest you to use display: inline-block; for the child element with the parent set to text-align: center;, well if that suffice your needs, than you can go for that too...

.fixed {
    position: fixed;
    width: 100%;
    height: 40px;
    background: tomato;
    text-align: center;
}

.center {
    display: inline-block;
    width: 300px;
    height: 40px;
    background: blue;
}

Demo 2

Just make sure you use text-align: left; for the child element, else it will inherit the text-align of the parent element.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...