不幸的是,据我所知,使用纯 CSS 是不可能的。
但是有一个解决方法。我在 Louis Hoebregts here 的 CSS-Tricks 上找到的
"在 JavaScript 中,您始终可以使用全局变量 window.innerHeight 获取当前视口的值。该值会考虑浏览器的界面,并在其可见性发生变化时更新。诀窍是存储视口值在 CSS 变量中并将其应用于元素而不是 vh 单元。
假设我们的 CSS 自定义变量是本示例的 --vh。这意味着我们将希望像这样在我们的 CSS 中应用它:"
CSS
.my-element {
height: 100vh; /* Fallback for browsers that do not support
Custom Properties */
height: calc(var(--vh, 1vh) * 100);
}
JavaScript
// First we get the viewport height and we multiple it by 1%
// to get a value for a vh unit
let vh = window.innerHeight * 0.01;
// Then we set the value in the --vh custom property to the
// root of the document
document.documentElement.style.setProperty('--vh', `${vh}px`);
“所以,我们告诉 JS 抓取视口的高度,然后将其向下钻取到总高度的 1/100,这样我们就有了一个值作为我们的视口高度单位值。然后我们礼貌地要求 JS 创建:root 中的 CSS 变量 (--vh)。
因此,我们现在可以像使用任何其他 vh 单位一样使用 --vh 作为我们的高度值,将其乘以 100 就得到了我们想要的完整高度。
[...]
我们可以通过监听 window resize 事件来更新 --vh 的值。这在用户旋转设备屏幕时非常方便,例如从横向到纵向,或者导航在滚动时移出视图。”
// We listen to the resize event
window.addEventListener('resize', () => {
// We execute the same script as before
let vh = window.innerHeight * 0.01;
document.documentElement.style.setProperty('--vh', `${vh}px`);
});
这是一个适合你的代码片段
// First we get the viewport height and we multiple it by 1% to get a value for a vh unit
let vh = window.innerHeight * 0.01;
// Then we set the value in the --vh custom property to the root of the document
document.documentElement.style.setProperty('--vh', `${vh}px`);
// We listen to the resize event
window.addEventListener('resize', () => {
// We execute the same script as before
let vh = window.innerHeight * 0.01;
document.documentElement.style.setProperty('--vh', `${vh}px`);
});
body {
background-color: #333;
margin:0;
}
.module {
height: 100vh; /* Use vh as a fallback for browsers that do not support Custom Properties */
height: calc(var(--vh, 1vh) * 100);
margin: 0 auto;
max-width: 30%;
}
.module__item {
align-items: center;
display: flex;
height: 20%;
justify-content: center;
}
.module__item:nth-child(odd) {
background-color: #fff;
color: #F73859;
}
.module__item:nth-child(even) {
background-color: #F73859;
color: #F1D08A;
}
<div class="module">
<div class="module__item">20%</div>
<div class="module__item">40%</div>
<div class="module__item">60%</div>
<div class="module__item">80%</div>
<div class="module__item">100%</div>
</div>