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()
andsign()
to give you a "boolean" value of0
or1
.When you have
0
or1
in a variable you can do conditional styles likepadding: 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
}
...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 */
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! */
Demo on CodePen, with fallbacks.
Note:
abs()
andsign()
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)
Update: if() lands Chrome! youtube.com/watch?v=Apn8ucs7AL0