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

时间:2010-05-17 19:55:45

标签: html css

所以我有一个问题,我觉得很常见,但我还没有找到一个好的解决方案。我想制作一个覆盖div覆盖整个页面...而不仅仅是视口。我不明白为什么这么难做...我已经尝试将body,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。

5 个答案:

答案 0 :(得分:202)

视口是最重要的,但您可能希望整个网站即使在滚动时也会变暗。为此,您希望使用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>

答案 1 :(得分:12)

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

答案 2 :(得分:1)

首先,我认为你误解了视口是什么。视口是浏览器用于呈现网页的区域,您不能以任何方式构建您的网站以任何方式覆盖此区域。

其次,似乎您的overlay-div不会涵盖整个视口的原因是因为您必须删除BODY和HTML上的所有边距。

尝试在样式表的顶部添加它 - 它会重置所有元素的所有边距和填充。使进一步的开发更容易:

* { margin: 0; padding: 0; }

编辑: 我更好地理解了你的问题。 Position: fixed; 可能会为你做好准备,正如Jonathan Sampson写的那样。

答案 3 :(得分:0)

我遇到了很多麻烦,因为我不想将覆盖层固定到位,因为我希望覆盖层内的信息可以在文本上滚动。我用过:

from pytest_cases import parametrize_with_cases, parametrize, fixture

datasetA = [10, 20, 30]
dbA_keys = range(3)

datasetB = [100, 200]  # just to see that it works with different sizes :)
dbB_keys = range(2)

@fixture(scope="module")
def dbA():
    #do setup
    yield datasetA
    #finalize

@parametrize(idx=dbA_keys)
def item_from_A(dbA, idx):
    yield dbA[idx]

@fixture(scope="module")
def dbB():
    #do setup
    yield datasetB
    #finalize

@parametrize(idx=dbB_keys)
def item_from_B(dbB, idx):
    yield dbB[idx]

@parametrize_with_cases('data', prefix='item_', cases='.')
def test_data(data):
    print(data)
    #do test

当然,中间的div需要一些内容,并且可能需要透明的灰色背景,但是我敢肯定您的要旨!

答案 4 :(得分:-6)

我看了上面的Nate Barr的答案,你似乎很喜欢。它与简单的

似乎没有什么不同
html {background-color: grey}
相关问题