简体   繁体   English

如何使绝对定位的div填充整个文档区域

[英]How to make an absolute positioned div fill the entire document area

I need to have an absolute div that is a child of only body fill the entire document area (window + any scroll area) -- width: 100% only fills the viewable screen 我需要有一个绝对div ,它是仅body的子级填充整个文档区域(窗口+任何滚动区域)-宽度:100%仅填充可见的屏幕

I prefer a CSS only solution but pure javascript is ok. 我更喜欢仅使用CSS的解决方案,但纯JavaScript可以。 I tried without success setting: 我尝试没有成功设置:

opaque.style.minHeight = Math.max(document.body.offsetHeight, document.body.scrollHeight);

I made a jsFiddle of the code below. 我在下面的代码中做了jsFiddle If you scroll down the output, you will see that the opaque div stops at whatever height the output window was when it was rendered. 如果向下滚动输出,您将看到不透明的div停止在呈现输出窗口时的高度。

In case you are wondering... it is to make an opaque overlay of all content in the div behind it (think slideshow). 如果您想知道...是要在它后面的div中覆盖所有内容的不透明覆盖(请考虑幻灯片放映)。 My only other solution is to disable scrolling, but this is problematic. 我唯一的其他解决方案是禁用滚动,但这是有问题的。

Thanks for any help. 谢谢你的帮助。

<div class="page-container"></div>    
<div id="opaque"></div>

body {
    width:100%;
}
.page-container {
    position: relative;
    max-width:978px; 
    width: 100%;
    min-height:2500px; 
    margin:0 auto -50px auto; 
    border:solid #999;
    border-width:2px;
    background: lightblue;
}

#opaque {
    position: absolute;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
    z-index: 100;
    background: grey;
    filter: alpha(opacity=70);
    opacity: 0.7;
}

Can use 可以使用

#opaque {
    position: fixed;
    top: 0;
    left: 0;
    right:0;
    bottom:0;
}

remove width:100% from body due to creates horizontal scrollbar 删除width:100%由于创建水平滚动条而从主体

Depending on use case it is often common to add class to body when using such an overlay that sets body overflow to hidden 根据使用情况,通常在使用此类覆盖将主体溢出设置为隐藏的覆盖时将类添加到主体

DEMO DEMO

您可以在身体上放置一个position: relative document对象,子元素在高度上将其用作参考点。

Using javascript to set one elements height equal to anothers 使用JavaScript将一个元素的高度设置为等于另一个

var o = document.getElementById('opaque');
var p = document.querySelector('.page-container');

o.style.height = window.getComputedStyle(p).getPropertyValue("height");

FIDDLE 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM