我有一个里面有图像的图层:
<div id="foo"><img src="url" /></div>
它是固定定位的:
#foo {
position: fixed;
}
但我也希望该图层在页面中水平居中。所以我尝试了:http : //jsfiddle.net/2BG9X/
#foo {
position: fixed;
margin: auto
}
#foo {
position: fixed;
left: auto;
}
但不起作用。关于如何实现的任何想法?
当您将元素fixed
放置到时,它会脱离文档流,即使margin: auto;
您想在文档流中也不起作用,请将元素嵌套在该放置的元素内,fixed
然后再margin: auto;
用于该元素。
演示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;
了child元素,否则它将继承text-align
父元素的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句