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

时间:2014-01-23 13:46:51

标签: html css css-position

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

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

它固定位置:

#foo {
    position: fixed;
}

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

#foo {
    position: fixed;
    margin: auto
}

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

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

但不起作用。知道如何实现它?

4 个答案:

答案 0 :(得分:9)

当你将一个元素定位到fixed时,它会离开文档流,即使margin: auto;也无效,如果你愿意,可以在fixed位置内嵌一个元素元素,而不是使用margin: auto;

Demo

Demo 2 (已将height添加到body元素,以便您可以滚动到测试

<强> 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;
}

有些人会建议您将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;
}

Demo 2

请确保您对子元素使用text-align: left;,否则它将继承父元素的text-align

答案 1 :(得分:1)

请尝试以下操作。

#foo {
    position: fixed;
    left: 50%;
    width: 30%;
    transform: translate(-50%, 0);
}

Fiddle

答案 2 :(得分:1)

使用transform: translate(-50%, 0);
示例代码:http://codepen.io/fcalderan/pen/uJkrE

CSS

div {
  position: fixed;
  border: 3px #555 solid;
  left: 50%;
  -webkit-transform: translate(-50%, 0);
  -moz-transform: translate(-50%, 0);
  -ms-transform: translate(-50%, 0);
  transform: translate(-50%, 0);
}

答案 3 :(得分:0)

这种方式不是跨浏览器,您必须为图层width:30%设置百分比宽度,并设置left:35%right:35%以及position:fixed
这是更好的,适用于所有浏览器RTL和LTR

相关问题