我在网站上工作,我需要设置一个 div 的高度和宽度来覆盖浏览器视口(viewport)的整个区域,就像许多现代网站一样。但是,我不能简单地将其高度设置为 100%,因为它的父元素是另一个 div,其高度必须 设置为大于浏览器窗口。还有另一种方法吗?
Here's代码示例设置类似于我的网站。
HTML
<div class="entireThing">
<div class="contentBox">
</div>
<div class="contentBox">
</div>
</div>
CSS
.entireThing {
height: 8000px;
width: 100%;
}
.contentBox {
height: 100%; /*This works only if parent is same size as window*/
}
最佳答案
5.1.2. Viewport-percentage lengths: the ‘vw’, ‘vh’, ‘vmin’, ‘vmax’ units
The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.
使用视口(viewport)百分比长度。在本例中,100vh
。
.contentBox {
height: 100vh;
}
您还可以使用 calc()
减去 10px
顶部/底部边距:
.contentBox {
height: calc(100vh - 20px); /* Subtract the 10px top/bottom margins */
margin: 10px;
color: white;
background-color: #222;
}
..值得指出的是您需要建立a new block formatting context在父元素上以 prevent the collapsing margins .
关于html - 当容器大于视口(viewport)时,将高度设置为浏览器视口(viewport)的 100%?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28005190/