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 Variables, 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 →

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.