CSS typed arithmetic is thrilling! It allows for new layout compositions and animation logic that were previously difficult to achieve. My first use of typed arithmetic was in this animation:
Before diving into the animation details, let’s clarify what typed arithmetic is and its significance for CSS.
Browser Support: Typed arithmetic is cutting-edge, with limited and experimental browser support. Examples in this article include videos and images for those whose browsers don’t support it yet. Check MDN or Can I Use for the latest support status.
The Types
To understand a “type” in CSS, think of TypeScript, then forget it. In CSS, a type describes the unit space a value occupies, called a data-type. Each CSS value belongs to a type, and CSS properties and functions accept only the expected data type(s).
– Properties like opacity or scale use a plain
– Width, height, and other box metrics use
– Functions like rotate() or conic-gradient() use an
– Animation and transition use
Note: CSS data types are identified by angle brackets:
There are more data types like
Not every data type is calculable. Types like
The Rules of Typed Arithmetic
Calculable data types have limitations and rules for mathematical operations.
Addition and Subtraction
Mixing types doesn’t work. Expressions like calc(3em + 45deg) or calc(6s – 3px) won’t produce logical results. Stick to the same data type when adding or subtracting.
You can add and subtract different units within the same type, like calc(4em + 20px) or calc(300deg – 1rad).
Multiplication
You can only multiply by a plain
Multiplying by a number is allowed because expressions like calc(10px * 10px) would result in invalid units like px², which don’t exist in CSS. CSS permits multiplying typed values by unitless numbers.
Division
Mixing incompatible types isn’t allowed. You can divide by a number, but what happens when dividing a type by the same type?
Hint: This is where it gets interesting.
Previously, calc(70px / 10px) was invalid. But starting with Chrome 140, this expression returns a valid number, 7 in this case. This is the major change enabled by typed arithmetic.
Is that all?!
Yes! This feature opens a world of creative possibilities, allowing for value conversions and mathematically conditioned values, as shown in the swirl example above.
To understand it, let’s look at a simplified swirl:
A container
The angle calculation is straightforward. I take the index of each element using sibling-index() and multiply it by 10deg. So, the first element with an index of 1 will be rotated by 10 degrees (1 * 10deg), the second by 20 degrees (2 * 10deg), the third by 30 degrees (3 * 10deg), and so on.
“`css
i { –angle: calc(sibling-index() * 10deg); }
“`
For the distance
Discover more from WIREDGORILLA
Subscribe to get the latest posts sent to your email.