为什么 + 或 - 必须在 Calc() 方法中用空格包围?

Why must a + or - be surrounded with whitespace from within the Calc() method?

最近我开始在 CSS 中使用 calc(...) 方法。我很快了解到,诸如 width: calc(100%-2) 之类的代码将不起作用,尽管在 - 运算符前后添加 white-space 将解决问题并且 calc 方法将正常运行。

经过一些研究后,我发现多篇博客文章都提到了 white-space 是必需的,许多人甚至指出了规范 (CSS3 8.1.1),其中指出:

In addition, whitespace is required on both sides of the + and - operators. (The * and / operaters can be used without whitespace around them.)

现在,很明显,规范告诉我们这些运算符必须用 white-space 包裹起来,但为什么呢?我已经在规范中进一步阅读(通过第 8.1.2-4 节),如果在这些附加部分中有解释,我不理解其中的原因。

简单来说,有人可以解释为什么指定 calc(100% - 1) 甚至 calc(100%/2) 是可接受的语法而不是 calc(100%-1) 吗?

- 字符是 CSS 标识符中允许的字符之一。从给定 here 的决议来看,他们似乎想防止使用不带空格的 - 可能引起的句法歧义,尤其是对于诸如 min-content 之类的关键字值(尽管 AFAIK 关键字值不是' calc() 内还不允许——如果我错了请纠正我)。

Not everyone agrees 不过这个分辨率。

Mozilla Developer Network解释得很好:

Note: The + and - operators must always be surrounded by whitespace. The operand of calc(50% -8px) for instance will be parsed as a percentage followed by a negative length, an invalid expression, while the operand of calc(50% - 8px) is a percentage followed by a minus sign and a length. Even further, calc(8px + -50%) is treated as a length followed by a plus sign and a negative percentage.

The * and / operators do not require whitespace, but adding it for consistency is allowed, and recommended.

我觉得你应该首先考虑CSSs如何识别一个长度。长度被定义为一个可选的符号,后跟一个模块和一个可选的度量单位(尽管许多属性实际上需要它):

<CSSlength> := [<sign>]<module>[<unit>]

因此,例如,有效的 CSS 长度为:

-3px
100em
+10pc
0
91
5%

像这样定义长度,CSS 引擎解析以下内容:

calc(100% -1px);

作为一个长度后跟另一个长度。在这种情况下,它将是 100% 后跟 -1px,这对 calc() 根本没有意义。这在相对MDN documentation page.

中也有解释

为了将两个长度相关联,您需要使用不同的运算符,因此,按照上述逻辑,您需要使用空格:

calc(100% - 1px);