我的图像里面有一个图像:
<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;
}
但不起作用。知道如何实现它?
答案 0 :(得分:9)
当你将一个元素定位到fixed
时,它会离开文档流,即使margin: auto;
也无效,如果你愿意,可以在fixed
位置内嵌一个元素元素,而不是使用margin: auto;
。
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;
}
请确保您对子元素使用text-align: left;
,否则它将继承父元素的text-align
。
答案 1 :(得分:1)
答案 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