3

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

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

演示

自己试试

笔记

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

4

1 回答 1

1

Is this working for you? 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 should be the wrapper for .content with a centered background and have a minimum-width of the .contents width+padding.

Update from comments:

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

We'll have to use a media-query, so when the width is at max 740px we change the background position. Oh and we set background-attachment to fixed again.

CSS added

@media screen and (max-width:740px) {
    div.background {
        background-position: -435px 0;
    }
}

I don't see why it is -435px ((1600-740)/2 would be 430) but it seems to be the most accurate value.

于 2012-07-02T16:16:55.447 回答