2010-05-17 103 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}