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

Pol*_*878 88 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> 
Run Code Online (Sandbox Code Playgroud)

如果存在JavaScript,我也会接受JavaScript解决方案,但我更倾向于使用一些简单的CSS.

Sam*_*son 212

视口是重要的,但您可能希望整个网站即使在滚动时也会变暗.为此,您要使用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; 
}
Run Code Online (Sandbox Code Playgroud)
<body>
  <div class="fadeMe"></div>
  <p>A bunch of content here...</p>
</body>
Run Code Online (Sandbox Code Playgroud)

  • @Marco不确定.说实话,如果没有明确要求支持10岁的浏览器,我不会再打扰了:) (27认同)
  • 那你们怎么在移动设备上做呢?http://bradfrostweb.com/blog/mobile/fixed-position/ (5认同)
  • 我可能错了,但是会在IE6中找到固定的工作吗?!我知道可能没有人关心IE6了. (3认同)
  • +1谢谢!我通过在叠加层上方添加一个弹出窗口来扩展您的示例:http://jsbin.com/okabo3/740/ (3认同)
  • 如果您使用“position:fixed”,请确保在小屏幕上进行测试,因为如果覆盖内容大于屏幕/窗口,则会出现问题。 (2认同)

Nat*_*arr 13

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

  • 最好的解决方案.您只需切换body的"overlayed"类,并使用该className将上面的样式应用于body. (2认同)
  • 请进一步解释此答案。我不理解斯维亚托斯拉夫的评论。 (2认同)