CSS Math Functions
CSS ships several math functions you can drop in anywhere a length, number, or angle is allowed. They let layouts respond fluidly without media queries.
The functions
| Function | What it does | Example |
|---|---|---|
calc() | Arithmetic on mixed units. | width: calc(100% - 32px) |
min(a, b, …) | Smallest value at render time. | width: min(90vw, 1100px) |
max(a, b, …) | Largest value. | font-size: max(16px, 1.2vw) |
clamp(min, ideal, max) | Constrains the ideal between a floor and a ceiling. | font-size: clamp(14px, 2vw, 22px) |
round(), mod(), rem() | Round, modulo, remainder on numeric values. | width: round(33.33%, 1px) |
Fluid type with clamp()
CSS
h1 {
/* Never smaller than 28px, never bigger than 56px,
scale with the viewport in between */
font-size: clamp(28px, 4vw + 0.5rem, 56px);
}
Replaces a stack of media queries with one declaration.
Common calc() recipes
| Goal | Expression |
|---|---|
| Four columns with 16px gutters | width: calc((100% - 48px) / 4) |
| Full-bleed inside a padded container | margin-inline: calc(50% - 50vw) |
| Sticky pane that respects header height | top: calc(var(--header) + 8px) |
Tip: Put spaces around
+ and - inside calc() — the parser requires it. calc(100% -8px) is invalid; calc(100% - 8px) works.Example
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>
<h1>CSS Math Functions</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Cap the heading between 28px (floor) and 56px (ceiling) with a fluid value in between.
h1 { font-size:
(28px, 4vw, 56px); }
A five-letter CSS function.
Discussion
Loading…