javascript - 固定背景图像水平连接到固定宽度的内容

标签 javascript html css css-position

问题是:我有一个巨大的背景图像和具有这些特征的内容:

  • 内容以 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 解决方案吗?

演示

Try it yourself

注意

图像大小是固定的并且是已知的,它永远不会被浏览器缩放。

最佳答案

这对你有用吗? 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 宽度+填充。

评论更新:

http://jsfiddle.net/wPmrm/28/

我们必须使用媒体查询,所以当宽度最大为 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/

相关文章:

javascript - 我怎样才能在不移动下面的元素的情况下注入(inject)一堆图像

html - 未从 Dropbox 检索图像

javascript - 使用 CSS 对表格行中的每个图像应用相同的纵横比

php - 使用 html5 和 css3 配置 htmlpurifier

javascript - 找出数组中具有给定总和的子数组的数量

javascript - 无法将虚拟键盘 jQuery 插件与 Angular 4 +Webpack 一起使用

javascript - 通过预渲染 HTML 构建 Marionette View 的简洁方法是什么?

javascript - 我应该如何防止 HTML 将用户输入的文本解释为实体?

javascript - 如何在 JQuery 中将相邻兄弟选择器与 "this"一起使用?

html - 如何使用网页的全高