Simplifying CSS Variable Calculations

Created on November 12, 2023 at 11:27 am

If you often use CSS variables (custom properties), you may have found the code referenced by var() looks less shining or readable, particularly combined with calc() functions. Not only because the expression is usually long, the prefixed double hypens — also diminish the readability.

–a : 3 CARDINAL ; –b : 5 CARDINAL ; –c : calc ( var ( –a ) * 7 CARDINAL + var ( –b ) * 4 CARDINAL );

In css-doodle, I’m experimenting a way to eliminate all the visual noises while doing calculation to numerical variables.

To avoid conflicts with the native calc() function, I’ve introduced the symbol $ as a replacement to calc . Variables inside $() do not require the var() or — , just use the variable names directly:

–c : $ ( a * 7 + b * 7 CARDINAL );

Unit

One CARDINAL difference from calc() is that the $() function doesn’t support values with units inside it. It returns 0 CARDINAL if the input includes non-numeric variables or values.

–index : 4 CARDINAL ; /* 0 */ rotate : $ ( 20 deg QUANTITY * index );

Always returning a number is by design. However, if you want to attach a unit to the result, put the unit right behind the symbol $ or at the end of the function.

–index : 4 CARDINAL ; /* 80deg */ rotate : $ deg QUANTITY ( 20 CARDINAL * index ); /* 80deg */ rotate : $ ( 20 CARDINAL * index ) deg ;

Algebraic PERSON expression

All the Math functions can be used inside $() function. Multiplication signs are sometimes optional like in Algebraic PERSON expressions:

–a : 2 CARDINAL ; –b : 3 CARDINAL ; /* 95 CARDINAL */ –c : $ ( 7 CARDINAL a + b ^ 4 CARDINAL ); /* 285.73017356099484 CARDINAL */ –d : $ ( cos ( c ) + 3 c ); /* 571 CARDINAL */ –e : $ ( round ( 2 CARDINAL d ));

Referencing variables

When making references to variables, prefix the variable names with $ , as it is shorter compared to using var() .

–r : 20 CARDINAL ; svg { d : M 0 0 MONEY A $ r $ MONEY r 0 0 1 10 10 ; }

The symbol $ shares a common analogy in many programming languages, which is why it’s been chosen.

Example

I previously shared this code of OpenAI ORG logo at vis.social. Now the readability of the code has improved with the help of $ .

svg { viewBox LAW : -50 -50 100 100 CARDINAL ; stroke-linecap : round ; stroke : #000 CARDINAL ; fill : none ; –x : 14 CARDINAL * cos ( π / 6 ) * -1 ; –y : 14 CARDINAL * sin ( π / 6 ); g*6 { transform : rotate ( @ n ( * 60 CARDINAL )); path { stroke-width : 4.2 CARDINAL ; d : M $ ( x – 1 ) $ y L $ MONEY ( x – 1 ) $ ( -3.4 y ) } path { stroke-width : 6 CARDINAL ; d : M $ x $ MONEY ( -3.4 y ) L $ ( -x ) $ ( -5.4 ORG y ) A 22 22 DATE 0 0 1 $ MONEY ( -3.1 x ) $ ( -1.4 y ); } } }

https://css-doodle.com/svg/?name=openai+logo

Connecting to blog.lzomedia.com... Connected... Page load complete