CSS Functions (calc, min, max, clamp)
CSS math functions let you compute values dynamically — mixing units, setting responsive constraints, and creating fluid layouts. calc() mixes units, min()/max() set limits, and clamp() combines both into one powerful function.
CSS Math Functions
- calc() — Mix units: width: calc(100% - 250px). The sidebar stays 250px, content fills the rest
- min() — Takes the SMALLER value: width: min(90%, 1200px). Width is 90% but never more than 1200px
- max() — Takes the LARGER value: font-size: max(16px, 1.2vw). Font is 1.2vw but never below 16px
- clamp(min, preferred, max) — Combined min+max: font-size: clamp(1rem, 2.5vw, 2rem)
- calc() with variables — width: calc(var(--sidebar-width) + var(--gap)). Dynamic calculations with design tokens
- Nested functions — width: min(calc(100% - 32px), 1200px). Functions inside functions
- Common patterns — calc(100vh - 60px) for content below a fixed header. calc(50% - 10px) for centered with offset
CSS Functions Code
/* Content area next to fixed sidebar */
.content {
width: calc(100% - 280px); /* 100% minus sidebar width + gap */
margin-left: auto;
}
/* Responsive container without media queries */
.container {
width: min(90%, 1200px); /* Same as: max-width: 1200px; width: 90%; */
margin: 0 auto;
}
/* Minimum font size guarantee */
h1 {
font-size: max(24px, 4vw); /* Never smaller than 24px */
}
/* Fluid spacing */
.section {
padding: clamp(1.5rem, 5vw, 4rem);
}
/* Full height minus header */
.main {
min-height: calc(100vh - 64px);
}
/* Centering with offset */
.tooltip {
left: calc(50% - 100px); /* Centered minus half tooltip width */
}
/* Dynamic grid with calc */
.grid-item {
width: calc((100% - 2 * var(--gap)) / 3); /* 3 columns with gaps */
}Tip
width: min(90%, 1200px) is the modern one-liner for responsive containers. It replaces the old 3-line pattern: width: 90%; max-width: 1200px; margin: 0 auto. Simpler, more composable, and works inside other calc() expressions.
Use rem for fonts, % for widths, vw/vh for full-screen layouts
Common Mistake
Forgetting that calc() requires spaces around operators. calc(100%-250px) silently fails — it must be calc(100% - 250px) with spaces. This is the #1 calc() debugging issue and produces no error, just broken layout.
Practice Task
Refactor with CSS functions: (1) Replace max-width: 1200px + width: 90% with width: min(90%, 1200px), (2) Use calc(100vh - 64px) for content below a fixed header, (3) Use clamp(1rem, 3vw, 2rem) for fluid heading font-size.
Quick Quiz
Key Takeaways
- CSS math functions let you compute values dynamically — mixing units, setting responsive constraints, and creating fluid layouts.
- calc() — Mix units: width: calc(100% - 250px). The sidebar stays 250px, content fills the rest
- min() — Takes the SMALLER value: width: min(90%, 1200px). Width is 90% but never more than 1200px
- max() — Takes the LARGER value: font-size: max(16px, 1.2vw). Font is 1.2vw but never below 16px