一种无需 JavaScript 即可计算视窗宽度和高度的方法,由 Temani Afif 在 CSS Tip 上分享。
@property --_w {
syntax: '<length>';
inherits: true;
initial-value: 100vw;
}
@property --_h {
syntax: '<length>';
inherits: true;
initial-value: 100vh;
}
:root {
--w: tan(atan2(var(--_w),1px)); /* screen width */
--h: tan(atan2(var(--_h),1px)); /* screen height*/
/* The result is an integer without unit */
}
这段代码向 Jane Ori 致敬,她最初发布了它并 写了说明 它如何工作。我不是数学天才,但我确实从高中时代就认识到 tan()
函数,它是一种根据给定角度计算直角三角形的对边和邻边比率的方法。

换句话说,tan()
将三角形的高(对边)除以宽(邻边)以产生一个角度。我们所做的就是提供它角度,即 tan( <angle> )
。
当我们有 calc()
时,为什么要这样做?问题是 calc()
无法执行我们需要的除法。所以,Jane Ori 巧妙地将 atan()
函数嵌套在其中:tan(atan())
。
巧妙之处在于 atan()
是 tan()
的逆函数,我们向它提供一个将宽度和高度值相除的比率:atan( <ratio> )
。这样,三角形的宽度和高度作为单独的参数被计算,在 tan()
函数执行操作之前,它提供了 tan()
函数计算角度正切所需的信息。
让 Jane 来总结一下
所以这个技巧在大多数情况下都有些愚蠢(可能也是为什么没有人早点指出它)因为我们使用了两个三角函数,而不是
calc()
实现目前无法执行的除法。
atan2( Height, Width )
=angle
tan( angle )
=Height / Width
Jane Ori, “CSS 类型转换到数值:tan(atan2()) 标量”
tan( atan2( Height, Width ) )
=Height / Width
您需要查看 Jane 的完整解释,其中包含另一个计算元素 font-size
值的示例。