我有一个里面有图像的图层:
http://jsfiddle.net/2BG9X/
http://jsfiddle.net/2BG9X/1/
<div id="foo"><img src="url" /></div>@H_404_4@它是固定的:
#foo { position: fixed; }@H_404_4@但我也希望图层在页面中水平居中.所以我试过了:
http://jsfiddle.net/2BG9X/
#foo { position: fixed; margin: auto }@H_404_4@和
http://jsfiddle.net/2BG9X/1/
#foo { position: fixed; left: auto; }@H_404_4@但不起作用.任何想法如何实现它?
解决方法
当你将一个元素定位到固定时,它就会离开文档流,甚至是margin:auto;如果你愿意,它将不起作用,将一个元素嵌套在固定的定位元素内,而不是使用margin:auto;为了那个原因.
@H_404_4@Demo
@H_404_4@Demo 2(增加了身体元素的高度,以便您可以滚动测试)
@H_404_4@HTML
<div class="fixed"> <div class="center"></div> </div>@H_404_4@CSS
.fixed { position: fixed; width: 100%; height: 40px; background: tomato; } .center { width: 300px; margin: auto; height: 40px; background: blue; }@H_404_4@有些人会建议你使用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; }@H_404_4@Demo 2 @H_404_4@只需确保使用text-align:left;对于子元素,否则它将继承父元素的text-align.