Logical Operations with CSS Variables CSS Custom Properties

Going beyond Binary Conditions for CSS Calculations, Ana Tudor takes it to a whole new level by introducing the logical operations (and, or, nand, nor, not, and xor) to CSS — all built on top of calc()

Very often, while using switch variables, I wish I could perform logical operations on them. We don’t have functions like not(var(--i)) or and(var(--i), var(--k)) in CSS, but we can emulate these and more with arithmetic operations in a calc() function.

Impressive!

Logical Operations with CSS Variables →

☝️ FYI: They’re officially called “CSS Custom Properties”, not “CSS Variables” 😉

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 calc() in Webkit

As mentioned before, CSS calc() was about to come to Chromium/Chrome (Webkit). Since about a week ago, the first part of the implementation has landed into the Canary builds:

Adds calc expressions to CSSPrimitiveValue. This enables simple (ie no mixing of percents with numbers/lengths) expressions to be evaluated on most properties.

No mixing yet, but quite sure that’ll land with the next commit 🙂

Simple -webkit-calc() test-cases →
Webkit trac: Changeset 107688 →

CSS calc() in Chromium/Chrome

Three days ago this was committed:

This is the parsing stage of calc. The expressions are evaluated and expression trees are generated. CSS values are not created yet – that will happen in a subsequent commit.

Looking forward to the next commits, as this feature will make things — such as flexible columns with a little border in a responsive layout — easier.

Note: calc() already works in IE9+ and Firefox4+ (with -moz vendor prefix).

Chromium Changeset 106166 →