css clamp for responsive typography

Create fluid, responsive typography that scales smoothly between minimum and maximum sizes using the clamp() function.

Explanation

  • clamp(min, preferred, max): Sets a value that scales between a minimum and maximum based on a preferred calculation.
  • min: The minimum value (lower bound) that will be returned.
  • preferred: The ideal value, typically using viewport units (vw) for fluid scaling.
  • max: The maximum value (upper bound) that will be returned.
  • Eliminates the need for multiple media queries for responsive font sizes.

Usage

To create fluid typography that scales with viewport width:

/* Basic fluid typography */
h1 {
  font-size: clamp(1.5rem, 5vw, 3rem);
}

/* Fluid paragraph text */
p {
  font-size: clamp(1rem, 0.5rem + 1vw, 1.25rem);
}

/* Fluid heading with calculation */
h2 {
  font-size: clamp(1.25rem, 1rem + 2vw, 2.5rem);
}

/* Fluid line height */
.content {
  line-height: clamp(1.5, 1.2 + 0.5vw, 2);
}

Example

/* Responsive heading system */
h1 {
  font-size: clamp(2rem, 1rem + 5vw, 4rem);
  line-height: 1.2;
}

h2 {
  font-size: clamp(1.5rem, 0.75rem + 3vw, 2.5rem);
}

h3 {
  font-size: clamp(1.25rem, 0.5rem + 2vw, 2rem);
}

/* Body text that scales smoothly */
body {
  font-size: clamp(1rem, 0.875rem + 0.5vw, 1.125rem);
}

/* Large display text for hero sections */
.hero-title {
  font-size: clamp(2.5rem, 2rem + 8vw, 6rem);
  letter-spacing: clamp(-0.02em, -0.01em + -0.5vw, -0.05em);
}