2016-11-24 58 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; 
}