CSS Functions

CSS includes powerful functions that compute values at runtime. The most useful day-to-day are calc(), min(), max(), clamp(), attr(), and color helpers like hsl() and color-mix().

1) calc() — Math with Units


.content{
  width: calc(100% - 260px);
  padding: calc(1rem + 2vw);
}
Content width uses calc()

You can mix units (%, px, rem, vw). Use spaces around operators: +, -, *, /.

2) min() and max() — Choose a Bound


.card{ width: min(420px, 90%); }
.tile{ height: max(120px, 12vh); }
width: min(420px, 90%)
height: max(120px, 12vh)

These are great for responsive bounds without media queries.

3) clamp(min, preferred, max) — Fluid Within Limits


h1{ font-size: clamp(18px, 2.5vw + 8px, 34px); }
.module{ width: clamp(220px, 50vw, 520px); }

Fluid title scales by viewport

Width uses clamp()
768px

4) attr() — Use Attribute Values


.label::after{
  content: " (" attr(data-unit) ")";
}
Download Size Response Time

In most browsers, attr() is mainly for content in pseudo-elements.

5) Color Functions: hsl(), Alpha, color-mix()


.swatch1{ background: hsl(210 80% 90%); }
.swatch2{ background: hsl(14 100% 50% / .25); } /* alpha */
.swatch3{ background: color-mix(in oklab, #1E88E5 60%, #43A047); }

hsl()

alpha channel

color-mix()

Use modern syntax like hsl(210 60% 50%) (space-separated) and / for alpha. color-mix() needs modern browsers; a fallback is provided.

Tips & Best Practices:

  • Prefer clamp() + min()/max() for responsive sizing without media queries.
  • Keep spaces around calc() operators for compatibility.
  • Combine with var() (CSS variables) for dynamic themes and runtime changes via JavaScript.
  • Provide graceful fallbacks for newer features like color-mix() using @supports or alternate colors.