min() and max() Functions in CSS

What min() Does

min() evaluates a list of values and uses whichever one is smallest at any given moment - useful for capping a value that would otherwise grow too large.

.container {
  width: min(90%, 1200px);
}

The container is 90% of its parent's width, unless that would exceed 1200px, in which case it is capped at 1200px instead - effectively a fluid width with a maximum ceiling.

What max() Does

max() is the opposite: it evaluates a list of values and uses whichever is largest - useful for enforcing a minimum floor on a value.

.sidebar {
  width: max(200px, 20%);
}

The sidebar takes 20% of the available width, unless that would be narrower than 200px, in which case it stays at a 200px minimum.

How These Relate to clamp()

In fact, clamp(MIN, VAL, MAX) is roughly equivalent to writing max(MIN, min(VAL, MAX)) - clamp() is really a convenient shorthand for a combination of min() and max() that comes up often enough to deserve its own function.

When to Reach for min()/max() Instead of clamp()

Use min() or max() directly when only one boundary matters - a maximum-width container with no minimum floor, for example. Reach for clamp() once both a floor and a ceiling are needed at the same time.

Nesting Them Together

.box {
  padding: max(16px, min(5%, 40px));
}

These functions can be nested inside one another for more advanced conditional sizing logic, though keeping expressions simple usually keeps a stylesheet easier to read and maintain.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.