CSS Switch-Case Conditions

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:

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.

A trick! Using @keyframes for state

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 like 100.001s so that if we delay by 100s, 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.


The post CSS Switch-Case Conditions appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.