Math Functions
Overview
CSS is incredibly smart. It can perform real-time math natively in the browser without relying on JavaScript or preprocessors like Sass. The calc() function allows you to mix totally different units together (like subtracting pixels from percentages). The min(), max(), and clamp() functions allow you to set fluid boundaries, drastically reducing the number of Media Queries you need to write for responsive design.
Syntax
/* 1. calc(): Mixing incompatible units */
/* Make the sidebar take up the full screen MINUS the 60px header */
.sidebar {
height: calc(100vh - 60px);
}
/* 2. min(): Pick the SMALLER of two values */
/* On mobile, it will be 90% wide. On huge screens, it caps at 1200px */
.container {
width: min(90%, 1200px);
}
/* 3. max(): Pick the LARGER of two values */
/* Ensure the padding never drops below 20px, but scales dynamically */
.card {
padding: max(20px, 2vw);
}
/* 4. clamp(): The holy grail (MIN, PREFERRED, MAX) */
/* The font starts at 1rem, scales fluidly with the screen, but caps at 2rem */
h1 {
font-size: clamp(1rem, 5vw, 2rem);
}Common Pitfalls
- Forgetting the spaces around the math operators in
calc().calc(100%-50px)will violently break and do nothing. You MUST use spaces around the minus/plus signs:calc(100% - 50px). - Misunderstanding how
min()works. Beginners often thinkmin(100%, 500px)means 'set a minimum width of 500px'. It's the exact opposite! It literally chooses the mathematically smaller value. If the screen is 300px wide, 100% is smaller than 500px, so it becomes 300px.
Interview Questions
clamp() function.clamp(MIN, IDEAL, MAX). It establishes an absolute floor, a dynamically scaling preferred value (usually utilizing viewport units), and an absolute ceiling. It is the modern replacement for complex media query typography.
Real-World Example
Using clamp to create a perfectly fluid responsive container without a single media query.
/*
On phones, the gap is 1rem.
As the screen grows, it scales fluidly up to 3rem on desktops.
*/
.grid-container {
display: grid;
gap: clamp(1rem, 2vw + 1rem, 3rem);
}Check Your Knowledge
Test your understanding of Math Functions with these quick questions.