CSS is yet to have a switch
rule or conditional if
, aside from the specific nature of @media
queries and some deep trickery with CSS custom properties. Let’s have a look at why it would be useful if we did, and look at a trick that is usable today for pulling it off.
Recent chatter about the possibility
While none of these things are usable today, there has been a good amount of chat about the concept of generic conditional CSS just in the last year:
- Brian Kardell proposed a
switch()
statement and Tab Atkins riff on it. - Jonathan Neal proposed a media query variation for conditional values that sparked quite a lot of conversation.
- Lea Verou proposed “higher level custom properties” (here’s a look at them from Bramus Van Damme) which seem extraordinarily useful.
So, yes. The demand for conditional CSS is there.
Imagine why conditional CSS would be useful
Perhaps a visual change after a certain amount of scrolling. A visual change after a numeric input is within a certain range. A component with a handful of states.
There is a whole genre of extremely popular JavaScript libraries for UI (e.g. React, Vue, etc.) that are essentially for building UI based on state. Clearly this is a developer need. If we could move that state-based styling to CSS, that’s all the less JavaScript we might need — and maybe a better separation of concerns.
A common theme
We already have custom properties in CSS, and we could base state-change logic on them, changing a block of styles as a side effect of the custom property changing to certain values.
It’s true that we have mechanisms for changing blocks of styles already. We can change class
through JavaScript, and that class
can apply whatever we like in CSS. But that doesn’t mean state-based styling in CSS wouldn’t be useful. We don’t always have the ability or may not want to write any JavaScript for this, and instead change custom properties in other ways (e.g. media queries, HTML changes, etc). Doing it in CSS means helping separate business logic and visual style logic.
@keyframes
for state
A trick! Using CSS @keyframes
can be used to switch
specific changes. Through the power of the animation
property, a possibility opens up to select exactly which frame to show, and have it pause exactly on that frame, effectively mimicking a switch-case statement or state-based styles.
Let’s see see this in action by playing with the animation-delay
property:
Here’s what’s happening in that Pen:
animation-delay
: Negative delay values force a specific frame (or between) to take effect (positive values don’t work that way). We’ll use this trick to force states.animation-play-state: paused
: We’re not actually animating anything, so the animation will stay paused.animation-duration
: The actual duration doesn’t matter, it just needs one so there is a time span to hold the different keyframes. We’ll make it a value like100.001s
so that if we delay by100s
, the last keyframe will still work. The duration needs to be longer than the delay value.
The first range input modifies the animation-delay
between a range of -100s
and 0s
.
A real-world use-case
Before we jump straight into the working example, it’s worth discussing this trick in more detail because there’s some nuances you ought to be aware of.
First off, the trick only works with numeric values. So, color values or strings because it’s strictly performing math.
Second, there’s the boolean trick. Consider a variable --value: 10
which can take any numeric value between 0 and 100. We want to apply color if the value is above 5. How do we know if the value is over or below 5? And even if we do know, how does that help actually help us?
--is-above-5: clamp(0, var(--value) - 5, 1)
--value | --is-above-5 | Result |
---|---|---|
0 | 0 | 0 – 5 = -5, clamp() forces a value no less than 0 |
2 | 0 | 2 – 5 = -3, clamp() forces a value no less than 0 |
5 | 0 | 5 – 5 = 0 |
7 | 1 | 7 – 5 = 2, clamp() forces a value no larger than 1 |
clamp()
is like a smarter calc()
, in that it allows us to strictly confine a computed value to range while declaring an ideal value. That range is all that is needed to achieve a boolean variable.
Write any math in the second parameter of the clamp()
and that will either output 0 (or below) or 1 (or above). Make sure not to write any math that might result in a number between 0 and 1.
Here’s how that works out:
The range input’s only job is to “broadcast” its value by defining a values for --value
, --min
and --max
, then modifying the --value
using an oninput
event. That is the most minimal thing that can be done get state-like behavior in CSS. No JavaScript needed.
Using CSS math functions, it is possible to infer the “completed” percentage of the progress bar from those same variables:
--completed: calc((var(--value) - var(--min) ) / (var(--max) - var(--min)) * 100);
Now, we know if the value is over a certain percentage, giving us yet another way to make changes by state:
--over-30: clamp(0, var(--completed) - 30, 1);
--over-70: clamp(0, var(--completed) - 70, 1);
/* ...and so on... */
OK, great, but how can we use this to select a specific keyframe? By using max()
function:
--frame: max(
calc(1 - var(--over-30)),
var(--over-30) * 2,
var(--over-70) * 3,
var(--is-100) * 4
);
The thing with CSS booleans is that there are many ways to use them to achieve a certain goal, and one must get creative, finding a formula which is short and readable.
In the above formula, the booleans will “toggle” a frame number if the boolean has the value of 1
. Since we are using a max
function, the the largest toggled frame number will be the computed value of --frame
.
Note that the color change has a slight transition. We could have done this with the background: currentColor;
on the fill area, which inherits the color from the parent, but I chose to use CSS Houdini to illustrate the power of assigning transitions to CSS variables by declaring its type
.
An example of a heavily-used CSS boolean trick can be viewed in the below Pen, which is a CSS-only component with lots of variables that allow a wide range of customization:
I am sure there are many other use cases for this little trick and am excited to see what else might be achieved by the creativity of the community.
Yet the oninput handler is JS, and the worst, eval kind.
It would be useful if we had conditionals and access to some DOM properties in CSS, but on the other hand just like finding weird inline event handlers is infuriating, imagine trying to manage a codebase where the logic can be in JS, HTML and CSS at the same time. We will need much more advanced CSS linters ;p
@MS – it is simply an example of one use case which I personally use. I see absolutely no problem with inline events for simple components which should work and be viewed as a black-box, where another developers should not even care what’s going on.
Imagine it as a Web-Component, which is the ultimate example of a black-box, and then you simply do not know and do not care how it does what it does, you only care it works well for you.
Anyway, this method described above is for highly complex scenarios.
Imagine you already have a component which does some calculations and you want to “translate” those calculations into different CSS styles, depending on some parameters. for example, a scroll event listener, and using the scrollTop value, you can simply provide that value to the CSS, and now the CSS suddenly have access to a dynamic data, which opens the door to many possibilities such as described in the article.
There can be so many things you can do with this, which I have yet to think of. I simply invented a tool, and not it’s up people to find ways to use it.
Just like a hacker, I sit, for years, almost 20 – sit and think – how can i manipulate css to do things its creators haven’t imagined it would be used for? I want to manipulate CSS to the extremes, bending it to my will, forcing it to the limits which are bound to my knowledge of the language and imagination, and imagination is key for finding those CSS-tricks.
Many thanks for pushing up the limits.
I see incredible potential here for simplifying management of color schemes. Instead of setting dozens of properties every time you want to invoke a color scheme, you can just refer to a frame from the color scheme animation in one line: https://codepen.io/jproffitt71/pen/bGBMVJx
This all makes me wonder if CSS should have something like a @properties keyword for defining groups of custom properties.
Ah, I see you reference a proposal for this right at the beginning: https://github.com/w3c/csswg-drafts/issues/5624
My bad. This is very exciting though.