2014-06-19 64 views
0

我目前正在開發一個網站。我想要一個具有以下屬性的背景div:CSS - 高度爲div的零,但已設置高度

#background { 
    background-image: url("../images/background.png"); 
    width: 100%; 
    height: 100%; 
    background-position: center; 
    z-index: 1; 
} 

而我的div基本上是<div id="background"></div>

但在我的網站上,背景div顯示0高度。有什麼方法可以解決它嗎?

回答

1

添加到您的風格:

position: absolute; 

但是請注意,這仍然取決於你的HTML和CSS的其餘部分。根據它,你可能更喜歡

position: fixed; 

Reference

+1

這是一個非常糟糕的主意。 – avrahamcool

+0

非常感謝!現在我可以轉到網站的下一部分了。 – mission712

1

。 檢查這個代碼
的html代碼:

<html> 
<body> 
    <div id="back"></div> 
</body> 
<html> 

CSS代碼:

html,body{ 
    width:100%; 
    height:100%; 
} 
#back{ 
    background:black; 
    height:100% important; 
    min-height:100%; 
    width:100%; 
} 

你可以看到jsFiddle

+2

'重要'是錯誤的(並且沒用)。 –

+0

你可以清楚:D但它沒有錯 –

+2

這是一個糟糕的做法,在這裏沒用,甚至沒有正確的語法... –

0

測試代碼,你有寬度和高度的100%,相對於它的父容器。如果#background的父項是正文,則必須確保該正文也具有100%,這又取決於其父HTML也具有大小。

這是默認行爲。如果你希望你的元素走出這個世界上,你可以使用:

position: absolute; 

position: fixed; 

猜你正在嘗試使用你的背景DIV作爲整個頁面的背景是這樣的解決方案我會用:

html, body { 
    margin: 0; 
    padding: 0; 
} 

#background { 
    position: fixed; 
    height: 100%; 
    width: 100%; 
    // Add your styles here 
} 
0

當使用百分比的高度/寬度時,請確保您有一個容器。所以你可以:

1)有一個設置高度的容器 - 這將使#background有容器的全高。

<div id="container"> 
    <div id="background"></div> 
</div> 

與CSS:

#container{ 
    height:250px; 
} 
#background{ 
    height: 100%; 
} 

jsfiddle

2)撰寫您#background元素裏面的內容。如果你有一個與height:100%空格,它將有一個0px的高度。

<div id="background"> 
    text 
</div> 
2

Demo

CSS

body, html { 
    height: 100% /* give height to your body and html */ 
} 
+0

[請勿將kbd用於不是用戶輸入的內容](http://meta.stackexchange.com/questions/181774/stricter-kbd-usage-rules) –

+0

@dystroy:沒有意識到這一點。謝謝! – 4dgaurav