calc, min, max, clamp

Math Functions Inside Values

calc, min, max, clamp

`calc()`, `min()`, `max()`, `clamp()` let you do arithmetic in CSS — mixing units freely.

4 min read Level 2/5 #css#calc#clamp
What you'll learn
  • Use `calc()` for mixed-unit math
  • Pick between values with `min` / `max`
  • Build fluid sizing with `clamp`

CSS has math functions. They mix units freely, so you can write things like “the page width minus 200px” in a single expression.

calc() — Arithmetic

.main {
  width: calc(100% - 250px);     /* full width minus the sidebar */
  height: calc(100vh - 80px);    /* full viewport minus the header */
  margin: calc(1rem + 4px);
  padding-block: calc(var(--space-3) * 2);
}

Operators: +, -, *, /. Spaces required around + and -.

min() — Smaller of Two

.container {
  width: min(90%, 1200px);   /* whichever is smaller */
}

A container that’s 90% of the screen — but never wider than 1200px.

max() — Larger of Two

button {
  padding: max(0.5rem, 1vw);   /* at least 0.5rem, more on big screens */
}

Useful for minimum sizes on responsive scaling.

clamp() — Between Two Bounds

clamp(min, ideal, max) — the workhorse for fluid sizing.

h1 {
  font-size: clamp(1.5rem, 4vw, 3rem);
}
  • At small screens: 1.5rem
  • On big screens: 3rem
  • In between: 4% of viewport width

The single most-used modern CSS function for typography.

Combining Functions

.gutter {
  padding: max(1rem, env(safe-area-inset-bottom));
}

env(...) reads environment values (notch insets on phones, etc.).

Math Beyond Sizing

:root {
  --col-count: 3;
  --gap: 1rem;
}

.col {
  width: calc((100% - (var(--col-count) - 1) * var(--gap)) / var(--col-count));
}

Three equally sized columns with a gap. Custom-property–driven math; change --col-count from a media query.

Up Next

CSS nesting — write rules inside rules.

Nesting →