Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

css-calc

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 calc(100%/2) is acceptable syntax but not calc(100%-1)?

like image 943
RLH Avatar asked Dec 22 '15 16:12

RLH


People also ask

How does the CALC () function work on values in CSS?

CSS calc() is a function used for simple calculations to determine CSS property values right in CSS. The calc() function allows mathematical expressions with addition (+), subtraction (-), multiplication (*), and division (/) to be used as component values.

What is Calc method in CSS?

calc() The calc() CSS function lets you perform calculations when specifying CSS property values. It can be used anywhere a <length> , <frequency> , <angle> , <time> , <percentage> , <number> , or <integer> is allowed.

What is whitespace in HTML?

Whitespace refers to characters which are used to provide horizontal or vertical space between other characters. Whitespace is often used to separate tokens in HTML, CSS, JavaScript, and other computer languages.

Can I use Calc in padding?

A solution for you would be to use CSS calc, it has good browser support and fixes your issue in quite a simple manner. The only downside here is that it doesn't calculate the padding-top in % but you simply cannot calculate padding-top in % from the height of the element unless you use javascript.


1 Answers

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.

like image 94
BoltClock Avatar answered Sep 16 '22 14:09

BoltClock