如何水平居中固定的定位元素

Man*_*olo 3 html css css-position

我有一个图像里面的图层:

<div id="foo"><img src="url" /></div>
Run Code Online (Sandbox Code Playgroud)

它是固定的:

#foo {
    position: fixed;
}
Run Code Online (Sandbox Code Playgroud)

但我也希望图层在页面中水平居中.所以我试过:http: //jsfiddle.net/2BG9X/

#foo {
    position: fixed;
    margin: auto
}
Run Code Online (Sandbox Code Playgroud)

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

#foo {
    position: fixed;
    left: auto;
}
Run Code Online (Sandbox Code Playgroud)

但不起作用.任何想法如何实现它?

Mr.*_*ien 9

当你将一个元素定位到fixed它时,它就会离开文档流margin: auto;,如果你愿意的话甚至不会工作,在一个fixed定位元素中嵌套一个元素而不是margin: auto;用于它.

演示

演示2 (添加heightbody元素,以便您可以滚动到测试)

HTML

<div class="fixed">
    <div class="center"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS

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

.center {
    width: 300px;
    margin: auto;
    height: 40px;
    background: blue;
}
Run Code Online (Sandbox Code Playgroud)

有些人建议你使用display: inline-block;父元素设置的子元素text-align: center;,如果满足你的需要,那么你也可以使用它...

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

.center {
    display: inline-block;
    width: 300px;
    height: 40px;
    background: blue;
}
Run Code Online (Sandbox Code Playgroud)

演示2

只需确保您使用text-align: left;子元素,否则它将继承text-align父元素.