在iOS 15.4中对Safari浏览器进行了各种更新。 增加的dvh单元对网络开发来说意义重大。
直到现在,iOS Safari中还存在一个问题,当开始滚动时,URL栏会变小,屏幕尺寸也会改变。 因此,有必要为 "大URL栏 "或 "小URL栏 "状态设置100%的高度,而仅用CSS就很难实现反映URL栏当前状态的100%的高度。 dvh解决了这个问题。
结论
可以写成height: 100dvh;
,其中height: 100%;
或height: 100vh;
之前被写成height: 100dvh;
。
以前的解决方案
直到现在,有几种模式可以在iOS Safari中实现100%的高度。
方案1:100%。
这种模式指定高度为百分比。 然而,这是一个麻烦的方法,因为如果你想达到100%高度的元素在HTML标签中处于较低的层次,你就必须为所有的元素写上100%。 这也是vh单元诞生前的老方法。
在这种情况下,可以实现反映URL栏状态的100%的高度,但将height: 100%;
传播到<html>
标签上是很困难的。
<!DOCTYPE html>
<html style="height: 100%">
<body style="margin: 0; color: white; font-family: sans-serif; height: 100%">
<div style="height: 100%">
<div
style="
height: 100%;
background-color: gray;
display: flex;
justify-content: center;
align-items: center;
"
>
<div>Center</div>
</div>
<div style="height: 100%; background-color: black; text-align: center">
<div>Test</div>
</div>
</div>
</body>
</html>
方案2:100vh。
自从CSS3中引入vh单位后,使用这种方式已经很普遍了。 其主要特点是不需要高度传播。
然而,其高度被固定为 "小URL栏 "的高度。
由于容器的高度较大,垂直居中的效果并不理想。
<!DOCTYPE html>
<html>
<body style="margin: 0; color: white; font-family: sans-serif">
<div>
<div
style="
height: 100vh;
background-color: gray;
display: flex;
justify-content: center;
align-items: center;
"
>
<div>Center</div>
</div>
<div style="height: 100vh; background-color: black; text-align: center">
<div>Test</div>
</div>
</div>
</body>
</html>
(方式3:JavaScript) 这一次,假设只用CSS来实现,但使用JavaScript,在过去已经可以实现100%的高度反映URL栏的状态。
然而,仅仅为了控制一个简单的显示器而编写JavaScript是很麻烦的。
新的解决方案。
新的解决方案,即dvh标签,将自动达到100%的高度,以反映URL栏的状态,只需替换以前使用的vh标签。
<!DOCTYPE html>
<html>
<body style="margin: 0; color: white; font-family: sans-serif">
<div>
<div
style="
height: 100dvh;
background-color: gray;
display: flex;
justify-content: center;
align-items: center;
"
>
<div>Center</div>
</div>
<div style="height: 100dvh; background-color: black; text-align: center">
<div>Test</div>
</div>
</div>
</body>
</html>
这是最好的! 🙌
从现在起,让我们用dvh代替vh。
注意事项。
dvh是一个新的单元,尚未广泛实施--在Safari 15.4之外,甚至谷歌浏览器也没有实现它。 因此,它应该总是与回退结合起来使用。
写在回退之后的CSS有优先权,可以在很多情况下使用,写法如下。
<div style="height: 100vh; height: 100dvh"></div>
本文由mdnice多平台发布