我正在网站上工作,我需要设置div的高度和宽度,以覆盖浏览器视口的整个区域,就像许多现代网站一样.但是,我不能简单地将其高度设置为100%,因为它的父元素是另一个div,其高度必须设置为大于浏览器窗口.还有另一种方法吗?
这是一个与我的网站类似的代码示例.
HTML
<div class="entireThing">
<div class="contentBox">
</div>
<div class="contentBox">
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
CSS
.entireThing {
height: 8000px;
width: 100%;
}
.contentBox {
height: 100%; /*This works only if parent is same size as window*/
}
Run Code Online (Sandbox Code Playgroud)
Jos*_*ier 14
5.1.2.视口百分比长度:'vw','vh','vmin','vmax'单位
视口百分比长度相对于初始包含块的大小.当初始包含块的高度或宽度改变时,它们相应地缩放.
使用视口百分比长度.在这种情况下,100vh.
.contentBox {
height: 100vh;
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用calc()减去10px上/下边距:
.contentBox {
height: calc(100vh - 20px); /* Subtract the 10px top/bottom margins */
margin: 10px;
color: white;
background-color: #222;
}
Run Code Online (Sandbox Code Playgroud)
..这是值得指出的,你需要在父元素上建立一个新的块格式化上下文,以防止折叠边距.