RLH RLH - 10 months ago 51
CSS Question

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

Recently I've started using the calc(...) method within CSS. I quickly learned that code such as:

width: calc(100%-2)
will not work, though adding white-space before and after the
operator will fix the problem and the calc method will function properly.

After doing a bit of research I found multiple blog posts reference that the white-space is required and many have even pointed to the specification (CSS3 8.1.1) which states:

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

Now, clearly, the spec tells us that these operators must be wrapped in white-space, but why? I've read further within the spec (through sections 8.1.2-4) and if it's explained in these additional portions, I'm not understanding the reasoning.

In simple terms, could someone explain why it was specified that
calc(100% - 1)
or even
is acceptable syntax but not

Answer Source

The - character is one of the allowed characters in CSS idents. Judging by the resolution given here, it seems they wanted to prevent syntactic ambiguities that could arise from using - without whitespace, especially with keyword values such as min-content (although AFAIK keyword values aren't yet allowed within calc() — correct me if I'm wrong).

Not everyone agrees with this resolution, though.