请参考以下示例:
我有一个网页与一个特别宽,居中的背景图像。我希望页面的主体宽度折叠到内容,并忽略包含背景的div。在给定的示例中,我有一个简化的示例来说明如何做到这一点:一个bg-outerdiv建立适当的页面宽度(200px宽),一个bg-innerdiv (400px宽)包含超宽图像。然后,我使用overflow:visible和负边距来尝试在不增加页面宽度的情况下将更宽的bg-inner居中。但是,正如示例所示,当浏览器窗口小于400px而不是200px时,就会出现水平滚动条。为什么会发生这种情况?有没有更好的方法?
谢谢——
编辑:这是我最终找到的一个副本,具有相似但略有不同的解决方案。不过我更喜欢wdm给出的答案。
重复文章:为什么负边距会影响我的页面宽度?
然而,这一个更好地解释了你想要完成的目标。
演示:http://jsfiddle.net/wdm954/L3U9c/
<div id="bg">
<div id="content">
Here is my content.
</div>
</div>
#bg {
background-color: red;
background-position: top center; /* for images */
}
#content {
margin-left: auto;
margin-right: auto;
position: relative;
left: 0px;
top: 0px;
width: 200px;
background-color: #ccc;
}
可以添加
body {
overflow-x: hidden;
}
我认为你所需要的只是3行CSS:
body {
background-image:url('myurl.jpg');
background-position:center;
background-size:cover;
}
如你所见:
<body>
<p>This is my document. Nothing else necessary</p>
<!-- any other content you desire -->
</body>