2016-11-24 60 views
0

我有一个网页,带有#wrap div居中页面的属性{margin:0 auto; }背景图片超过#wrap div

我的封面图片应该在宽度上(超过#wrap)和780px的高度。

由于#cover div位于居中的#wrap div内,因此图像无法从左侧的绝对点0开始。

我该如何解决这个问题?

我的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; 
    } 
+1

请提供必要的HTML代码来重现您的问题。 –

+0

“我的封面图片应占用所有页面的宽度和780px的高度。” 请澄清:图像应该是'body'还是'#wrap'的宽度? – Moob

回答

0

它不清楚你想达到的目标。从你的问题描述中可以看出,听起来像是,你需要一个固定的全宽背景。有很多方法可以实现这一点。在这种情况下,您应该绝对定位#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。为了清晰起见,我会将其移出,但不管怎样,修​​复方法都是一样的。

0

如果你想使你的背景位置是从x = 0和y =你需要设置background-position: top left,而不是center 0。 background-size: cover你说的背景应该覆盖所有的div,所以在左边的位置,你可以从右边和底部松开零件。

解决办法:

#cover { 
    background-position: top left; 
}