我有一个网站,其 #wrap div 位于页面的中心,属性为 { margin: 0 auto;
我的封面图片应占据整个主体的宽度(超过 #wrap)和 780 像素的高度。
图像不是从左侧的绝对点 0 开始,因为 #cover div 在居中的 #wrap div 内。
我该如何解决这个问题?
我的 HTML:
<div id="wrap">
<div id="cover"></div>
</div>
我的 CSS:
#wrap {
width: 960px;
margin: 0 auto;
}
#cover {
background-image: url(bg.jpg);
background-attachment: fixed;
background-clip: border-box;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
height: 780px;
z-index: -10;
}
最佳答案
不清楚您要实现的目标。根据您对问题的描述,听起来您想要一个固定的全 Angular 背景。有很多方法可以实现这一点。在这种情况下,您应该绝对定位 #cover
并为其指定 100% 宽度和 780px
的固定高度。
我在这个例子中使用了百分比,纯粹是为了让它更适合代码段窗口。我还使 #wrap
更高,并赋予它半透明的背景颜色,这样您就可以看到 #cover
背景的固定性质。
html,
body {
margin: 0;
height: 100%;
min-height: 100%;
}
#wrap {
width: 80%;
height: 120%;
margin: 0 auto;
background: rgba(0, 0, 0, 0.1);
z-index: 1;
}
#cover {
background-image: url(https://placekitten.com/300/300);
background-attachment: fixed;
background-clip: border-box;
background-position: top left;
background-repeat: no-repeat;
background-size: cover;
width: 100%;
height: 78%;
position: absolute;
top: 0;
left: 0;
z-index: -10;
}
<div id="wrap">
<div id="cover"></div>
Lorem ipsum sed diam eget risus varius blandit sit amet non magna.
</div>
仅供引用。为了代码清晰起见,您不应将 #cover
元素放在 #wrap
中,除非您希望/期望它以某种方式受其约束。在您的情况下, #cover
和 #wrap
元素在位置上不相关,因为 #cover
应该是整个页面的背景,而不仅仅是#wrap
。为了清楚起见,我将其移出,但无论如何修复都是一样的。
关于css - 背景图片超过#wrap div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40788725/