HTML & CSS Tip of the Week

The min() and max() functions

Published on


From my experience, clamp() gets a lot of love compared to the min() and max() functions.

Granted, it’s often the most useful one, but both min() and max() can be extremely useful as well.

Unlike clamp(), which requires three values, both min() and max() functions accept as many values as you want to give them.

For example, we could do something like this:

.element {
  inline-size: min(100%, 960px, 60ch);
}

I’ve started using min() in a lot of places that I used to use max- properties, such as max-inline-size.

One common example would be for container/wrapper classes:

.wrapper {
  width: min(100% - 32px, 960px);
  margin-inline: auto;
}

In this case, I’m choosing the smaller value between 100% - 32px and 960px.

The downside to these is often that they’re a little tricky to read quickly, but anytime readability becomes an issue in CSS, a few custom properties always makes life easier.

.wrapper {
  --max-width: 960px;
  --padding: 16px;

  width: min(100% - var(--padding) * 2, var(--max-width));
}

This might seem like more work than it’s worth, but I tend to like using custom properties for this type of thing as it allows for easy modifications when needed.