问题是:我有一个巨大的背景图像和具有这些特征的内容:
- 内容以
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 的包装器,背景居中,最小宽度为 .contents 宽度+填充。
评论更新:
我们必须使用媒体查询,所以当宽度最大为 740px 时,我们更改背景位置。哦,我们再次将 background-attachment 设置为 fixed。
添加了 CSS
@media screen and (max-width:740px) {
div.background {
background-position: -435px 0;
}
}
我不明白为什么它是 -435px((1600-740)/2 将是 430),但它似乎是最准确的值。
关于javascript - 固定背景图像水平连接到固定宽度的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11223676/