Codectionary / Developer documentation / CSS

calc(), min(), max(), clamp()

These functions let you compute CSS values dynamically. calc() performs math between different units. min() and max() pick the smallest or largest of a list of values. clamp(min, preferred, max) is especially powerful for fluid, responsive sizing - it uses the preferred value but never goes below min or above max.

Syntax

calc(expression)
clamp(min, preferred, max)

Examples

calc() for Mixed-Unit Math

Combining different units in a single calculation.

.sidebar-offset {
  width: calc(100% - 250px); /* fills remaining space next to a fixed 250px sidebar */
}

.centered-minus-gap {
  margin-top: calc(2rem + 10px);
}

clamp() for Fluid Typography

The most common modern pattern - text that scales with the viewport but stays within safe bounds.

h1 {
  font-size: clamp(1.75rem, 4vw + 1rem, 3.5rem);
  /* never smaller than 1.75rem, never larger than 3.5rem,
     scales fluidly with viewport width in between */
}

Parameters and values

  • calc() (function): Performs math, mixing different units
  • min() (function): Uses the smallest of the given values
  • max() (function): Uses the largest of the given values
  • clamp(min, val, max) (function): Fluidly scales val, bounded between min and max

Best practices

  • Use clamp() for fluid typography instead of setting different font-size values in multiple media queries
  • Use calc() whenever you need to mix units, like subtracting a fixed sidebar width from a 100% fluid container
  • Use min() to cap a fluid width so it never grows unreasonably large on very wide screens, without needing a max-width media query
  • Remember these functions can be nested and combined for sophisticated responsive behavior entirely within CSS, with no JavaScript needed

At a glance

Purpose
Presentation and layout
File extension
.css
Runs in
Web browsers
Usually used with
HTML and JavaScript

Specifications & further reading

Related CSS documentation