Topic 21 of 30
Calc(), clamp(), min(), max()
Overview
CSS mathematical functions perform calculations directly in CSS, eliminating many cases where you'd need JavaScript or media queries. clamp() is especially powerful for fluid typography and responsive spacing.
Syntax
css
/* calc() — mix units */
.sidebar { width: calc(100% - 280px); }
.card { padding: calc(var(--spacing) * 2); }
.hero { height: calc(100vh - 64px); }
/* clamp(min, preferred, max) */
h1 { font-size: clamp(1.5rem, 4vw, 3.5rem); }
.container { padding: clamp(16px, 4vw, 48px); }
.card { width: clamp(280px, 30%, 400px); }
/* min() / max() */
.image { width: min(600px, 90vw); } /* never wider than 90vw */
.sidebar { width: max(200px, 20%); } /* never narrower than 200px */
/* Fluid spacing scale */
:root {
--space-sm: clamp(0.5rem, 2vw, 1rem);
--space-md: clamp(1rem, 4vw, 2rem);
--space-lg: clamp(2rem, 6vw, 4rem);
}Common Pitfalls
- In calc(), always add spaces around operators: calc(100% - 32px) works; calc(100%-32px) doesn't.
- clamp() doesn't work if min > max — you'll get an invalid value. Always ensure min < preferred < max.
- Interview tip: clamp(1rem, 4vw, 2rem) creates fluid typography that scales with viewport width between 1rem and 2rem — no media queries.
Real-World Example
Fully fluid responsive layout without any media queries:
example
css
/* Fluid typography — no media queries needed */
:root {
--heading-xl: clamp(2rem, 6vw + 1rem, 5rem);
--heading-lg: clamp(1.5rem, 4vw, 3rem);
--body: clamp(1rem, 1.5vw, 1.25rem);
}
h1 { font-size: var(--heading-xl); }
h2 { font-size: var(--heading-lg); }
body { font-size: var(--body); }
/* Fluid card that's never too wide or too narrow */
.product-card {
width: clamp(240px, calc(33% - 32px), 380px);
padding: clamp(16px, 4%, 32px);
}
/* Responsive container without media queries */
.container {
max-width: min(1200px, 95vw);
margin-inline: auto;
padding-inline: max(16px, calc((100vw - 1200px) / 2));
}