问题是:我有一个巨大的背景图像和具有这些特征的内容:
- 内容以
margin: auto;
居中,宽度固定 - 内容的位置相对于图像(就像它适合图像的中间一样)
- 此连接仅是水平的(垂直滚动按预期移动所有内容)
实际上,这在固定在背景图像上的桌面设备上工作正常。
但问题是:当我调整窗口大小直到它小于内容时,内容固定在左侧,但背景图像仍然居中,正如预期的那样。在这种情况下,两个元素之间的连接会丢失。
我有这个 JavaScript 可以解决问题,但这当然是我想避免的一些开销,因为由于计算,它在任何时候都不流畅:
$(window).resize(function(){
container.css('left', (body.width() - img.width()) / 2);
});
我也尝试过这样的事情:
<div id="test" style="
position: absolute;
z-index: 0;
top: 0;
left: 0;
width: 100%:
height: 100%;
background: transparent url(path) no-repeat fixed center top;
"></div>
但这会导致上述相同的问题。
这个问题有什么优雅的CSS解决方案吗?
演示
自己尝试一下
注意
图像大小是固定且已知的,并且永远不会被浏览器缩放。
这对你有用吗? http://jsfiddle.net/wPmrm/24/
.HTML
<div class="background">
<div class="content">
CONTENT
<br><br>
This example works fine until you the viewport size gets smaller than this content. After that the image isn't sticky anymore.
<br><br>
And check out vertical scrolling.
<div style="height:1500px;"></div>
END
</div>
</div>
.CSS
div.background {
min-width: 740px;
background: url('http://placehold.it/1600x1050') top center fixed no-repeat;
}
div.content {
width: 700px;
height: 2000px;
margin: auto;
padding: 50px 20px;
background: none;
opacity: 0.7;
color: #333;
}
.background 应该是具有居中背景的 .content 的包装器,并且具有 .content 宽度+填充的最小宽度。
从评论更新:
http://jsfiddle.net/wPmrm/28/
我们必须使用媒体查询,因此当宽度最大为 740px 时,我们会更改背景位置。哦,我们将背景附件再次设置为固定。
添加了 CSS
@media screen and (max-width:740px) {
div.background {
background-position: -435px 0;
}
}
我不明白为什么它是 -435px(((1600-740)/2 将是 430),但它似乎是最准确的值。