我有一个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%;
}
可以这样做吗?谢谢
答案 0 :(得分:2)
使用position: fixed
时,您还需要指定元素位置的值。
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%;
}
答案 1 :(得分:1)
你可以看到演示页面:
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%;
}