Multi-Value CSS Properties With Optional Custom Property Values

Imagine you have an element with a multi-value CSS property, such as transform: optional custom property values:

.el {
  transform: translate(100px) scale(1.5) skew(5deg);
}

Now imagine you don’t always want all the transform values to be applied, so some are optional. You might think of CSS optional custom property values:

.el {
  /*         |-- default ---| |-- optional --| */
  transform: translate(100px) var(--transform);
}

But surprisingly using optional custom property values like this does not work as intended. If the --transform variable is not defined the whole property will not be applied. I’ve got a little “trick” to fix this and it looks like this:

.el {
  transform: translate(100px) var(--transform, );
}

Notice the difference? There is a fallback defined in there that is set to an empty value: (, )

That’s the trick, and it’s very useful! Here’s what the specification has to say:

In an exception to the usual comma elision rules, which require commas to be omitted when they’re not separating values, a bare comma, with nothing following it, must be treated as valid in var(), indicating an empty fallback value.

This is somewhat spiritually related to the The CSS Custom Property Toggle Trick that takes advantage of a custom property having the value of an empty space.

Demo

Like I said, this is useful and works for any multi-value CSS property. The following demo shows it using text-shadow, background, and filter in addition to the transform example we just discussed.

See the Pen CSS var – Fallback To Nothing by Yair Even Or (@vsync) on CodePen.

Some properties that accept multiple values, like text-shadow, require special treatment because they only work with a comma delimiter. In those cases, when the CSS custom property is defined, you (as the code author) know it is only to be used in a situation where a value is already defined where the custom property is used. Then a comma should be inserted directly in the custom property before the first value, like this:

--text-shadow: ,0 0 5px black;

This, of course, inhibits the ability to use this variable in places where it’s the only value of some property. That can be solved, though, by creating “layers” of variables for abstraction purposes, i.e. the custom property is pointing to lower level custom properties.

Beware of Sass compiler

While exploring this trick, uncovered a bug in the Sass compiler that strips away the empty value (,) fallback, which goes against the spec. I’ve reported the bug and hope it will be fixed up soon.

As a temporary workaround, a fallback that causes no rendering can be used, such as:

transform: translate(100px) var(--transform, scale(1));

Multi-Value CSS Properties With Optional Custom Property Values originally published on CSS-Tricks. You should get the newsletter and become a supporter.

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-5Result
000 – 5 = -5, clamp() forces a value no less than 0
202 – 5 = -3, clamp() forces a value no less than 0
505 – 5 = 0
717 – 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.