|<<>>|2 of 299 Show listMobile Mode

Using calc-size in CSS

Published by marco on

The following video shows not only when and how to use calc-size(), it also mixes in advice on generating timing functions for animations, sprinkles CSS variables throughout, and even uses overflow: clip combined with an absolutely positioned element to reveal more content without disturbing the layout.

Animate and do math on things like height: auto with interpolate-size and calc-size() by Kevin Powell (YouTube)

The syntax for calc-size() is, as Kevin says, “weird”; you have to pass two parameters: the first is the name of the logical size you’d like to use, while the second parameter is a formula that uses the placeholder size, which accepts the value of the first parameter. In a sense you are passing the argument, along with a lambda that accepts that argument.

The following CSS sets the inline (horizontal in LTR and RTL) size of an element to be whatever the intrinsic size of the element would have been, given the size of its children, plus 3rem (where rem is the font size of the root element (MDN)).

inline-size: calc-size(max-content, size + 3rem);

This video accompanies Kevin’s article for the 12 days of code 2024, if you’d rather read about it, with more code examples.