允许div覆盖整个页面而不是容器内的区域

Jui*_*icy 79 css

我正试图在整个屏幕上制作一个半透明的div.我试过这个:

#dimScreen
{
    width: 100%;
    height: 100%;
    background:rgba(255,255,255,0.5);
}
Run Code Online (Sandbox Code Playgroud)

但这并不涵盖整个屏幕,它只覆盖div内的区域.

Mic*_*idt 153

添加position:fixed.然后,当您滚动时,封面会固定在整个屏幕上.
也可以添加,margin: 0; padding:0;以便它不会在封面周围留出一些空间.

#dimScreen
{
    position:fixed;
    padding:0;
    margin:0;

    top:0;
    left:0;

    width: 100%;
    height: 100%;
    background:rgba(255,255,255,0.5);
}
Run Code Online (Sandbox Code Playgroud)

如果它不应该粘在固定的屏幕上,请使用 position:absolute;

CSS Tricks也有一篇关于全屏属性的有趣文章.

编辑:
刚刚看到这个答案,所以我想添加一些额外的东西.
就像评论中提到的丹尼尔艾伦兰登一样,加上top:0; left:0;可以肯定的是,封面贴在屏幕的顶部和左侧.

如果你的一些元素位于封面的顶部(因此它不包括所有内容),那么添加z-index.数字越高,涵盖的级别越高.

  • 显然有一个问题:如果position:fixed元素有一个带有css变换的祖先,那么它将相对于祖先而不是视口进行修复.https://developer.mozilla.org/en-US/docs/Web/CSS/position#Values (2认同)

Mr.*_*ien 17

您还需要将父元素设置100%

html, body {
    height: 100%;
}
Run Code Online (Sandbox Code Playgroud)

演示(更改background为演示目的)


此外,当你想覆盖整个屏幕时,似乎你想要dim,所以在这种情况下,你需要使用position: fixed;

#dimScreen {
    width: 100%;
    height: 100%;
    background:rgba(255,255,255,0.5); 
    position: fixed;
    top: 0;
    left: 0;
    z-index: 100; /* Just to keep it at the very top */
}
Run Code Online (Sandbox Code Playgroud)

如果是这样的话,那就不是你需要的了 html, body {height: 100%;}

演示2

  • 也许任何父母都有"位置:亲戚".不起作用.建议`position:fixed`代替. (2认同)

Con*_*rey 12

这样就可以了!

div {
  height: 100vh;
  width: 100vw;
}
Run Code Online (Sandbox Code Playgroud)


小智 5

Use position:fixed this way your div will remain over the whole viewable area continuously ..

give your div a class overlay and create the following rule in your CSS

.overlay{
    opacity:0.8;
    background-color:#ccc;
    position:fixed;
    width:100%;
    height:100%;
    top:0px;
    left:0px;
    z-index:1000;
}
Run Code Online (Sandbox Code Playgroud)

Demo: http://www.jsfiddle.net/TtL7R/1/