使 Div 覆盖整个页面(不仅仅是视图) ?

所以我有一个问题,我认为是相当普遍的,但我还没有找到一个很好的解决方案。我想做一个覆盖 div 覆盖整个页面... 不只是视图。我不明白为什么这么难做... 我已经尝试设置身体,html 高度为100% 等,但没有工作。以下是我目前掌握的信息:

<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。

159833 次浏览

The viewport is all that matters, but you likely want the entire website to stay darkened even while scrolling. For this, you want to use position:fixed instead of position:absolute. Fixed will keep the element static on the screen as you scroll, giving the impression that the entire body is darkened.

Example: 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>

First of all, I think you've misunderstood what the viewport is. The viewport is the area a browser uses to render web pages, and you cannot in any way build your web sites to override this area in any way.

Secondly, it seems that the reason that your overlay-div won't cover the entire viewport is because you have to remove all margins on BODY and HTML.

Try adding this at the top of your stylesheet - it resets all margins and paddings on all elements. Makes further development easier:

* { margin: 0; padding: 0; }

Edit: I just understood your question better. Position: fixed; will probably work out for you, as Jonathan Sampson have written.

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

I looked at Nate Barr's answer above, which you seemed to like. It doesn't seem very different from the simpler

html {background-color: grey}

I had quite a bit of trouble as I didn't want to FIX the overlay in place as I wanted the info inside the overlay to be scrollable over the text. I used:

<html style="height=100%">
<body style="position:relative">
<div id="my-awesome-overlay"
style="position:absolute;
height:100%;
width:100%;
display: block">
[epic content here]
</div>
</body>
</html>

Of course the div in the middle needs some content and probably a transparent grey background but I'm sure you get the gist!