CSS:让 div 滑过另一个 div(即,使用 div 作为背景)

CSS: make div slide over another div (i.e., use a div as background)

我有一个 div 作为页面背景,其他 div 显示在它上面。

然而,当用户滚动时,背景 div 也会滚动。我希望在内容 div 滚动时修复它。

这是我的实际代码:

#background {
    z-index: 1;
    width: 100%;
    height: 100vh;
    position: fixed;
}
#content {
    z-index: 99;
    position: absolute;
    top: 2em;
    padding: 1em 1em;
    width: 100%;
}

这能做到吗?谢谢

可以看到演示页面:

body, html, main {
    /* important */
    height: 100%;
}

.cd-fixed-bg {
    min-height: 100%;
    background-size: cover;
    background-attachment: fixed;
    background-repeat: no-repeat;
    background-position: center center;
}

.cd-fixed-bg.cd-bg-1 {
  background-image: url("http://farm5.static.flickr.com/4056/4228935406_93ff14c971.jpg");
}
.cd-fixed-bg.cd-bg-2 {
  background-image: url("http://farm5.static.flickr.com/4056/4228935406_93ff14c971.jpg");
}
.cd-fixed-bg.cd-bg-3 {
  background-image: url("http://farm5.static.flickr.com/4056/4228935406_93ff14c971.jpg");
}
.cd-fixed-bg.cd-bg-4 {
  background-image: url("http://farm5.static.flickr.com/4056/4228935406_93ff14c971.jpg");
}

.cd-scrolling-bg {
    min-height: 100%;
}

HERE MY DEMO

使用 position: fixed 时,您还需要指定元素位置的值。

A jsfiddle 证明了这一点:

HTML:

<div id="background"></div>
<div id="content">
    This is the content
</div>

CSS:

#background {
    z-index: 1;
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    background-image: url(https://wallpaperscraft.com/image/metal_lines_stripes_light_shiny_silver_18401_1920x1080.jpg);
}
#content {
    z-index: 99;
    position: absolute;
    top: 2em;
    padding: 1em 1em;
    width: 100%;
    color: blue;
    font-size: 300%;
    height: 400%;
}