Ex:calc(10px + 2px);
is correct
but
calc(10px +2px);
gives out an error
or
calc(10px - 2px);
is correct
but
calc(10px -2px);
gives out an error. However, this doesn’t apply to other operators
Ex:calc(10px + 2px);
is correct
but
calc(10px +2px);
gives out an error
or
calc(10px - 2px);
is correct
but
calc(10px -2px);
gives out an error. However, this doesn’t apply to other operators
2
Answers
The requirement for whitespaces before and after the "+" or "-" operators in the CSS
calc()
function is a syntax rule designed to avoid potential parsing conflicts and improve readability.The
calc()
function allows you to perform mathematical calculations within CSS property values. For example:In this example, the
calc()
function subtracts20px
from100%
to calculate the final width.The reason for requiring whitespaces before and after the "+" or "-" operators is to distinguish them from other uses of "+" and "-" within CSS. CSS uses these symbols for various purposes, like defining positive and negative values, specifying relative positions, etc.
Without whitespaces, the CSS parser might have difficulty distinguishing between an arithmetic operator inside the
calc()
function and other CSS rules. Consider this example:In this case, the parser might interpret
100%-20px
as a single value rather than recognizing it as an expression to evaluate with thecalc()
function. This could lead to invalid CSS or unexpected behavior.By requiring whitespaces, the parser can reliably identify arithmetic operations within
calc()
and avoid such parsing conflicts. Additionally, it enhances code readability by making it clearer where calculations are taking place within the CSS rule.For the
+
operator, the operation might get a little more complicated thancalc(10px + 2px);
. I mean something likecalc(5px + -1px);
is actually more complicated, and it can’t becalc(5px+-1px);
.For the
-
operator, how CSS is supposed to know whether the-
is the minus operator or a part of a negative number? I mean logically though.Also, the whitespaces make the code nice to read, for humans.
Learn more about the CSS
calc()
function in the documentation.