First of all, calc()
is not nestable 1. But for what you need, you shouldn't need to nest it. You can use parentheses to set the order of operations (as long as they are legal):
height: calc(50vw - (1vw / 1vh) * 3);
但那是不合法,原因如下:
- division by concrete units (
rem
, px
, pt
) 2 is not possible in calc()
. Not even if you do 1px / 1px
. The browser won't equate that to 1
.
- 即使按单位划分是可能的,并且浏览器足够智能,可以得出屏幕比例
1vw/1vh
,减法的第二部分将产生一个数值(例如,如果屏幕是正方形,则该值将为 3,因此您的计算结果将是calc(50vw - 3)
)。这又是不合法的:3
... 什么?px
, vw
, rem
?
有关详细信息,请参阅以下文档calc() https://drafts.csswg.org/css-values-3/#calc-notation.
结论:据我所知,没有办法使用 CSS 来获取屏幕比例。但使用 JavaScript 就相当简单了:
const setRatio = () => {
document.body.style.setProperty('--vw', self.innerWidth / 100);
document.body.style.setProperty('--vh', self.innerHeight / 100);
}
setRatio();
window.addEventListener('resize', setRatio)
.box {
height: calc(50vw - var(--vw) / var(--vh) * 3px);
border: 1px solid red;
}
<div class="box"></div>
1 - According to this answer https://stackoverflow.com/a/36414853/1891677, calc()
should be nestable. For a period of time, due to an oversight in its grammar, nesting was not possible. Today it's possible, in both theory and practice.
But we still can't add numeric values with unit values, just as we can't divide by unit values.
2 - for the purpose of this answer, percentage %
is also considered a concrete layout unit. That's because when used in directional properties (height
, max-width
, etc) it's calculated as percentage of the relevant dimension of the reference ancestor, on that direction. In other words, it's not a division by 100
.