DEV Community

George Adamson
George Adamson

Posted on • Edited on

Polyfill for CSS sign() and abs()

sign()

CSS sign() is not well supported but can be "polyfilled" with calc() & clamp():

Given...

  --input: 10; /* <-- Any number */
Enter fullscreen mode Exit fullscreen mode

...then sign() can be calculated using:

  --num: calc(var(--input) * infinity); 
  --sign: clamp(-1, var(--num), 1);
Enter fullscreen mode Exit fullscreen mode

The code above is equivalent to:

  --sign: sign(var(--input));
Enter fullscreen mode Exit fullscreen mode

Handy if you're attempting conditional logic and you need 0's and 1's instead of numbers. (What? Why? Read more about Binary Linear Interpolation).

How it works:

  1. Multiply by infinity to give us 0 or +/-infinity to avoid rounding errors when dealing with very small decimals. Tip: If you know your input numbers will never be between -1 & 1 then you can skip the calc().
  2. Round to the nearest -1, 0 or 1.

Demo on CodePen.

abs()

If you also need CSS abs(n) then simply use sqrt(pow(n,2)) instead: Demo on CodePen.
Combined with sign() you can derive "truthy" 0 or 1 from any number.

Top comments (0)