当容器大于视口时,将高度设置为浏览器视口的 100%?
Set height to 100% of browser viewport when container is bigger than viewport?
我在网站上工作,我需要像许多现代网站一样设置 div 的高度和宽度以覆盖浏览器视口的整个区域。但是,我不能简单地将其高度设置为 100%,因为它的父元素是另一个 div,其高度 必须 设置为大于浏览器 window。还有另一种方法吗?
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.
使用视口百分比长度。在这种情况下,100vh
.
.contentBox {
height: 100vh;
}
您还可以使用 calc()
减去 10px
top/bottom 边距:
.contentBox {
height: calc(100vh - 20px); /* Subtract the 10px top/bottom margins */
margin: 10px;
color: white;
background-color: #222;
}
..值得指出的是,您需要建立 a new block formatting context on the parent element in order to prevent the collapsing margins.
我在网站上工作,我需要像许多现代网站一样设置 div 的高度和宽度以覆盖浏览器视口的整个区域。但是,我不能简单地将其高度设置为 100%,因为它的父元素是另一个 div,其高度 必须 设置为大于浏览器 window。还有另一种方法吗?
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.
使用视口百分比长度。在这种情况下,100vh
.
.contentBox {
height: 100vh;
}
您还可以使用 calc()
减去 10px
top/bottom 边距:
.contentBox {
height: calc(100vh - 20px); /* Subtract the 10px top/bottom margins */
margin: 10px;
color: white;
background-color: #222;
}
..值得指出的是,您需要建立 a new block formatting context on the parent element in order to prevent the collapsing margins.