2010-05-17 294 views
76

所以我有一個問題,我認爲是相當普遍的,但我還沒有找到一個好的解決方案。我想使覆蓋div覆蓋整個頁面...而不僅僅是視口。我不明白爲什麼這是很難做...我已經嘗試設置身體,HTML高度爲100%等,但這是行不通的。以下是我迄今爲止:使Div覆蓋整個頁面(不只是視口)?

<html> 
<head> 
    <style type="text/css"> 
    .OverLay { position: absolute; z-index: 3; opacity: 0.5; filter: alpha(opacity = 50); top: 0; bottom: 0; left: 0; right: 0; width: 100%; height: 100%; background-color: Black; color: White;} 
    body { height: 100%; } 
    html { height: 100%; } 
    </style> 
</head> 

<body> 
    <div style="height: 100%; width: 100%; position: relative;"> 
     <div style="height: 100px; width: 300px; background-color: Red;"> 
     </div> 
     <div style="height: 230px; width: 9000px; background-color: Green;"> 
     </div> 
     <div style="height: 900px; width: 200px; background-color: Blue;"></div> 
     <div class="OverLay">TestTest!</div> 
    </div> 


    </body> 
</html> 

我還開放給在JavaScript的解決方案如果存在的話,但我寧願只使用一些簡單的CSS。

+0

能讀也更這裏:http://stackoverflow.com/questions/1938536/how-to-make-the-height-really-100/1938592# 1938592 – 2010-05-17 22:13:38

+0

這可以通過jQuery實現嗎? – 2016-04-26 03:52:29

回答

181

視口是重要的,但您可能希望整個網站即使在滾動時也保持黑暗。爲此,您要使用position:fixed而不是position:absolute。固定會在您滾動時使元素在屏幕上保持靜態,從而給人留下整個身體變暗的印象。

舉例:所有的http://jsbin.com/okabo3/edit

div.fadeMe { 
    opacity: 0.5; 
    background: #000; 
    width:  100%; 
    height:  100%; 
    z-index: 10; 
    top:  0; 
    left:  0; 
    position: fixed; 
} 
<body> 
    <div class="fadeMe"></div> 
    <p>A bunch of content here...</p> 
</body> 
+3

我可能錯了,但是會在IE6中定位工作?我知道可能沒人關心IE6了。 – 2010-05-17 22:04:11

+22

@Marco不確定。說實話,如果沒有明確要求支持10歲的瀏覽器,我不打擾了:) – Sampson 2010-05-18 01:31:30

+5

那麼你們如何在移動設備上做到這一點? http://bradfrostweb.com/blog/mobile/fixed-position/ – incarnate 2012-05-30 10:36:05

1

首先,我想你誤會視口是什麼。視口是瀏覽器用於呈現網頁的區域,您不能以任何方式構建您的網站以覆蓋此區域。

其次,似乎你的疊加DIV將不包括整個視口的原因是因爲你必須取消對身體和HTML的所有利潤。

嘗試在樣式表頂部添加它 - 它會重置所有元素上的所有邊距和填充。使得進一步開發更簡單:

* { margin: 0; padding: 0; } 

編輯: 我明白你的問題更好。正如Jonathan Sampson所寫,Position: fixed;可能會爲你工作。

+1

您不應從* everything *中移除填充和邊距。讓這些人迴歸許多像按鈕和表單輸入這樣的元素可能非常費力。 – Sampson 2010-05-17 20:02:09

+1

在我看來,它只是一種非常簡單的方式,可以在所有瀏覽器中更好地處理所有事情。今天可能不會像以前那樣適應IE5,但我仍然把它作爲我在樣式表中編寫的第一件事情之一。 – 2010-05-17 20:04:15

+3

@Arve它讓你關閉,但最好使用經過時間檢驗的重置表。查看http://meyerweb.com/eric/tools/css/reset/獲取更多信息 - 你一定會喜歡的,我向你保證:) – Sampson 2010-05-17 20:06:20

10
body:before { 
    content: " "; 
    width: 100%; 
    height: 100%; 
    position: fixed; 
    z-index: -1; 
    top: 0; 
    left: 0; 
    background: rgba(0, 0, 0, 0.5); 
} 
+2

最好的解決方案。您只需切換「覆蓋」類的body,然後使用該className將上述樣式應用於body。 – 2013-08-04 01:38:24

+1

請解釋這個答案更多。我不明白Sviatoslav的評論。 – 2016-06-01 19:07:02

-6

我看着內特巴爾的回答上面,你似乎很喜歡。它似乎沒有從簡單的很不同

html {background-color: grey}