DEV Community

George Adamson
George Adamson

Posted on • Edited on

Numeric comparison in CSS (for conditional logic)

Conditional logic in CSS is tantalisingly close.

Until CSS supports if() and else then we have to make do with workarounds.

Others, such as Lea Verou, have written superb guides about using binary logic to perform conditionals in CSS, using CSS Variables with values of 0 or 1.

Often however, we have ranges or numbers other than 0 or 1 in our CSS Variables so it would be handy if we could compare numeric values and drive logic from them.

TLDR: We can test for equality, less-than and greater-than by using a combination of calc(), abs() and sign() to give you a "boolean" value of 0 or 1.

When you have 0 or 1 in a variable you can do conditional styles like padding: calc(25px * var(--bool) + 10px * (1 - var(--bool))).

In JS we might simply write:

if (a === b) {
  // Apply some styles
}

if (a > b) {
  // Apply some styles
}
Enter fullscreen mode Exit fullscreen mode

...but the best we could hope for in CSS right now is to set boolean variables like the following, and to use them in Binary Linear Interpolation:

--isEqual:       /* Some magical logic here */
--isGreaterThan: /* Some other magical logic */
Enter fullscreen mode Exit fullscreen mode

Well there is a way using calc(), and the more recent abs() and sign(), to compare numbers and return 0 or 1.

Like this...

--isNotEqual: sign(abs(calc(var(--a) - var(--b))));
--isEqual:    calc(1 - var(--isNotEqual));

--isLessThan:    sign(max(0, calc(var(--b) - var(--a))));
--isGreaterThan: sign(max(0, calc(var(--a) - var(--b))));

--isLessThanOrEqual:    calc(1 - var(--isGreaterThan));
--isGreaterThanOrEqual: calc(1 - var(--isLessThan));

/* I'd welcome any suggestions for smarter ways to derive these! */
Enter fullscreen mode Exit fullscreen mode

Demo on CodePen, with fallbacks.

Note: abs() and sign() have only partial browser support but they can be achieved using older syntax. At time of writing only Safari & Firefox supported them.

Top comments (1)

Collapse
 
georgeadamson profile image
George Adamson

Update: if() lands Chrome! youtube.com/watch?v=Apn8ucs7AL0