CSS Variables and Reduced Motion

Great usage of CSS Custom Properties in combination with calc() by Steve Gardner to cater for users who have prefers-reduced-motion set to reduce:

By setting --duration to 0 it basically behaves like a binary condition for a CSS calculation. Simple and effective 🙂

(Personally I’d set it to either 0 or 1 – and not 0.5. That way the math is kept easy and it becomes a true binary toggle)

⁉️ Not sure what prefers-reduced-motion is? Check out CSS-Tricks’ Introduction to the Reduced Motion Media Query to get up to speed.

Conditions for CSS Calculations

In CSS we have feature queries (@supports) available to create ifelse-like structs. What if we could extend our means of using conditions in CSS?

Roman Komarov provides us with a clever technique – which involves using CSS Custom Properties, calc(), and some binary logic – to implementing this type of conditions on a per CSS rule basis. The simplest way to explain it is to just show it:

:root {
    --is-big: 0;

.is-big {
    --is-big: 1;

.block {
    padding: calc(
        25px * var(--is-big) +
        10px * (1 - var(--is-big))
    border-width: calc(
        3px * var(--is-big) +
        1px * (1 - var(--is-big))

The lines where * var(--is-big) is used are applied when the value of that CSS Variable is 1 (true). The lines where * (1 - var(--is-big)) is used are applied when said value is 0 (false).

In the example above it’d be much easier/better to define two different CSS blocks (one for just .block, and one for .block.is-big (or .is-big .block depending on the HTML structure)). Perhaps some scenarios where JavaScript changes the value of a CSS variable could provide us with a few interesting use cases.

Conditions for CSS Variables →

CSS Variables: var(--subtitle);

As per usual, great talk by Lea Verou:

The key takeaway about CSS Custom Properties to me is the very first one Lea mentioned: they’re just properties like the other CSS properties we already know. This means that the normal behavior of inheritance is in place, you can manipulate them from within media queries, and you can even get/set them via style attributes or even JavaScript:

const el = document.querySelector('#my-elem');

// Get
var foo = window.getComputedStyle(el).getPropertyValue('--foo');

// Set
el.style.setProperty('--foo', newValue);

I’ve created pens for the background mouse position follower, and for the CSS scroll indicator.

See the Pen CSS Variables: Follow Mouse Position by Bramus (@bramus) on CodePen.