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 →

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Join the Conversation

5 Comments

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.