skip to Main Content

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


  1. 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:

    width: calc(100% - 20px);
    

    In this example, the calc() function subtracts 20px from 100% 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:

    /* Ambiguous CSS */
    width: calc(100%-20px);
    

    In this case, the parser might interpret 100%-20px as a single value rather than recognizing it as an expression to evaluate with the calc() 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.

    Login or Signup to reply.
  2. For the + operator, the operation might get a little more complicated than calc(10px + 2px);. I mean something like calc(5px + -1px); is actually more complicated, and it can’t be calc(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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search