Responsive Typography with Container Queries

Scale font sizes, line heights, and heading levels based on container width using CSS container queries for truly adaptive typography in components.

Component Patterns

Detailed Explanation

Responsive Typography via Container Queries

Typography that adapts to its container rather than the viewport is one of the most practical uses of container queries. A heading inside a narrow sidebar needs smaller text than the same heading in a wide hero section.

The CSS

.text-container {
  container-type: inline-size;
  container-name: text-area;
}

.adaptive-heading {
  font-size: 1.25rem;
  line-height: 1.4;
}

@container text-area (min-width: 400px) {
  .adaptive-heading {
    font-size: 1.75rem;
    line-height: 1.3;
  }
}

@container text-area (min-width: 700px) {
  .adaptive-heading {
    font-size: 2.5rem;
    line-height: 1.2;
  }
}

Progressive Scaling

The heading starts at a comfortable reading size for narrow spaces, then scales up through two additional breakpoints. Each size comes with an adjusted line-height for optimal readability at that scale.

Body Text Adjustment

You can apply the same principle to body text and spacing:

@container text-area (min-width: 700px) {
  .content p {
    font-size: 1.125rem;
    max-width: 65ch;
  }
}

Using Container Query Units

CSS also provides container query length units: cqw (1% of container width), cqh (1% of container height), cqi (1% of inline size), cqb (1% of block size):

.fluid-heading {
  font-size: clamp(1rem, 4cqi, 3rem);
}

This creates truly fluid typography that scales smoothly with the container width, clamped between minimum and maximum sizes.

Use Case

Use this pattern for headings, article text, and any typography that appears in widgets or components placed in containers of varying widths, such as dashboard panels, card grids, and sidebar widgets.

Try It — CSS Container Query Builder

Open full tool