iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

FunctionWhat it doesExample
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

GoalExpression
Four columns with 16px gutterswidth: calc((100% - 48px) / 4)
Full-bleed inside a padded containermargin-inline: calc(50% - 50vw)
Sticky pane that respects header heighttop: 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 &raquo;</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); }

Test yourself

Q1. Which function picks the smallest value at render time?
Q2. Which function constrains a value between a floor and ceiling?
Q3. Inside `calc()`, why does `100% -8px` fail to parse?

Discussion

Loading…