liveBook · Manning

Calc()

As explained in CSS in Depth, Second Edition

The CSS calc() function computes a value from arithmetic involving CSS values and units.

The CSS calc() function performs arithmetic on CSS values, making it possible to combine units such as em and svw or derive dimensions from existing variables. section 2.4.2 section 3.2.1

Use calc() when the browser should calculate a relationship rather than preserve a trial-and-error number.

  • Combine responsive and accessible sizing, such as calc(0.5em + 1svw), so text scales with the viewport while retaining an em-based component. section 2.4.2
  • Write spaces around addition and subtraction operators; calc() supports addition, subtraction, multiplication, and division. section 2.4.2
  • Replace unexplained offsets with relationships, such as calc(var(--columns-width) - 3em), which subtracts known padding from a variable width. section 3.2.1

A smoothly scaling base font size

Define the root size with :root { font-size: calc(0.5em + 1svw); }. The em portion incorporates user font settings, while svw adds a viewport-responsive scalar. Resize the browser to observe a gradual change instead of breakpoint jumps. section 2.4.2

:root {
  font-size: calc(0.5em + 1svw);
}

Inspect the compact CSS listing for the responsive root font-size pattern. section 2.4.2

How CSS in Depth, Second Edition covers it

How deep it goes
Defines four arithmetic operators, explains whitespace requirements, and demonstrates responsive font and variable-based width calculations.
Examples
Uses responsive root typography and a column width reduced by its combined horizontal padding.
What it assumes
Uses CSS declarations, relative units, viewport units, and custom properties as the surrounding vocabulary.
What you can do after
Apply calc() to build smoothly scaling font sizes and derive widths from variables instead of unexplained constants.
How it connects
Connects viewport units, em and rem units, clamp(), CSS custom properties, and box-model sizing.

Also explained in

Compare how 3 books explain calc() →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of CSS in Depth, Second Edition. The section links point to the parts of the book it draws on.