Home

Simplifying CSS Variable Calculations

13 September 2023

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;
--b: 5;
--c: calc(var(--a) * 7 + var(--b) * 4);

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);

Unit

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

--index: 4;

/* 0 */
rotate: $(20deg * 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;

/* 80deg */
rotate: $deg(20 * index);

/* 80deg */
rotate: $(20 * index)deg;

Algebraic expression

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

--a: 2;
--b: 3;

/* 95 */
--c: $(7a + b^4);

/* 285.73017356099484 */
--d: $(cos(c) + 3c);

/* 571 */
--e: $(round(2d));

Referencing variables

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

--r: 20;

svg {
  d: M 0 0 A $r $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 logo at vis.social. Now the readability of the code has improved with the help of $.

svg {
  viewBox: -50 -50 100 100;
  stroke-linecap: round;
  stroke: #000;
  fill: none;

  --x: 14 * cos(π/6) * -1;
  --y: 14 * sin(π/6);

  g*6 {
    transform: rotate(@n(*60));
    path {
      stroke-width: 4.2;
      d: M $(x - 1) $y
         L $(x - 1) $(-3.4y)
    }
    path {
      stroke-width: 6;
      d: M $x $(-3.4y)
         L $(-x) $(-5.4y)
         A 22 22 0 0 1 $(-3.1x) $(-1.4y);
    }
  }
}

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