CSS can perform dynamic mathematical calculations directly inside stylesheets. The modern CSS Values and Units specification includes powerful arithmetic and comparative functions: calc(), min(), max(), clamp(), and modern rounding functions.
calc() allows you to perform addition (+), subtraction (-), multiplication (*), and division (/) mixing completely different units (like subtracting fixed pixels from 100% width):
.full-width-minus-sidebar {
/* Subtracts a 300px sidebar from full container width */
width: calc(100% - 300px);
}
.hero-fullheight {
/* 100% viewport height minus a fixed 70px navigation header */
height: calc(100vh - 70px);
}
In calc(), the plus (+) and minus (-) operators MUST be surrounded by whitespace! calc(100% - 20px) is valid; calc(100%-20px) is completely invalid because the browser parses -20px as a negative length.
/* min() takes the smaller value: caps width at 800px on large screens */
.article-container {
width: min(800px, 90vw);
}
/* max() takes the larger value: ensures font size never drops below 14px */
.caption {
font-size: max(14px, 1.2vw);
}
clamp(MIN, PREFERRED, MAX) restricts a value between an absolute floor and ceiling while allowing it to scale fluidly in between:
/* Fluid Headline: Minimum 1.75rem, scales at 4vw, maximum 3.5rem */
h1 {
font-size: clamp(1.75rem, 4vw + 1rem, 3.5rem);
}
/* Fluid Page Padding: 16px on mobile, grows up to 64px on desktop */
.page-wrapper {
padding-inline: clamp(1rem, 5vw, 4rem);
}
Boost your CSS and front-end development proficiency by exploring these closely connected topics:
Understand margins, borders, padding, content and the universal box-sizing fix.
Master 1D alignment, justify-content, align-items, flex-wrap and responsive flow.
Build powerful two-dimensional grid layouts with template areas and fr units.
Eliminate styling conflicts and master selector weights from 0,0,0,1 to !important.