Skip to main content
Practice Problems

CSS functions: calc(), clamp(), min(), max()

CSS Math Functions

CSS provides powerful math functions that allow dynamic calculations directly in stylesheets, reducing the need for media queries and JavaScript.


calc()

calc() performs arithmetic operations with different units:

css
.sidebar { width: calc(100% - 300px); /* Full width minus fixed sidebar */ } .section { padding: calc(1rem + 2vw); margin-top: calc(var(--header-height) + 20px); }

Rules:

  • Supports +, -, *, /
  • + and - require spaces around them: calc(100% - 20px)
  • * and / don't require spaces but at least one operand must be a number for *, and the divisor must be a number for /
  • Can nest: calc(calc(100% - 40px) / 3)

min()

Returns the smallest value from a list:

css
.container { width: min(90%, 1200px); /* Whichever is smaller */ } h1 { font-size: min(5vw, 3rem); /* Responsive but capped */ }

max()

Returns the largest value from a list:

css
.sidebar { width: max(250px, 20%); /* At least 250px */ } p { font-size: max(16px, 1.2vw); /* Never smaller than 16px */ }

clamp()

clamp(min, preferred, max) — the value is the preferred unless it goes below min or above max:

css
/* Fluid typography */ h1 { font-size: clamp(1.5rem, 4vw, 3rem); /* At least 1.5rem, ideally 4vw, at most 3rem */ } /* Fluid container */ .container { width: clamp(320px, 90%, 1200px); } /* Fluid spacing */ section { padding: clamp(1rem, 3vw, 4rem); }

Comparison Table

FunctionSyntaxUse Case
calc()calc(a op b)Mix units, arithmetic
min()min(a, b, ...)Cap maximum size
max()max(a, b, ...)Set minimum size
clamp()clamp(min, pref, max)Range-bound values

Practical Examples

Fluid Typography System

css
:root { --text-sm: clamp(0.875rem, 1vw, 1rem); --text-base: clamp(1rem, 1.2vw, 1.125rem); --text-lg: clamp(1.25rem, 2vw, 1.5rem); --text-xl: clamp(1.5rem, 3vw, 2.5rem); --text-2xl: clamp(2rem, 4vw, 3.5rem); }

Responsive Layout Without Media Queries

css
.card { width: min(100%, 400px); padding: clamp(1rem, 3vw, 2rem); margin: max(1rem, 2vw); }

Important:

clamp() is especially powerful for fluid typography and fluid spacing, often eliminating the need for multiple media queries. It's supported in all modern browsers.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems