Fitting Text to a Container

Modern CSS techniques for responsive text that adapts to any screen size

Introduction: The Text Fitting Challenge

Modern web design often requires text that dynamically adjusts to fill its container perfectly. Whether it's a hero headline that should span the full width of a banner, a pricing card that needs consistent visual weight, or a navigation item that must utilize available space efficiently, text fitting is a common challenge developers face.

Historically, achieving this required JavaScript libraries, clever SVG hacks, or accepting fixed dimensions that didn't adapt to responsive layouts. The web development community has progressively developed better solutions, and we're now at an exciting point where native CSS support is on the horizon.

The techniques we'll explore range from immediately usable modern CSS to bleeding-edge features that will become standard. Understanding these approaches helps you make informed decisions about which solution fits your project's needs and browser support requirements.

Traditional Approaches: Where We Started

JavaScript-Based Solutions

Before modern CSS provided viable alternatives, developers relied heavily on JavaScript to calculate and apply appropriate font sizes. Libraries like FitText.js became popular for this purpose, using JavaScript to measure text dimensions and adjust font-size accordingly.

These solutions typically work by measuring the container width, measuring the text at a base font size, calculating the ratio between them, and applying a scaled font-size. While functional, they introduce performance overhead, require JavaScript execution on page load and resize, and can cause layout shifts as fonts recalculate.

fittext-example.js
1// Traditional FitText.js approach2document.querySelectorAll('.fit-text').forEach(element => {3 const containerWidth = element.parentElement.offsetWidth;4 const textWidth = element.scrollWidth;5 const baseFontSize = parseFloat(getComputedStyle(element).fontSize);6 const scaleRatio = containerWidth / textWidth;7 element.style.fontSize = baseFontSize * scaleRatio + 'px';8});

SVG-Based Text Fitting

An alternative approach uses SVG's ability to scale text based on viewBox dimensions. By wrapping text in an SVG element and dynamically setting the viewBox to match the text's bounding box, developers could create fluid text that fills its container.

This technique has advantages: it works reliably across browsers, leverages SVG's scaling capabilities, and can be combined with CSS for styling. However, it introduces SVG markup overhead, has accessibility considerations, and limits some CSS text properties.

svg-fit-text.html
1<svg width="100%" viewBox="0 0 400 60">2 <text x="50%" y="50%" dominant-baseline="middle" 3 text-anchor="middle" font-size="48">4 Fluid Text5 </text>6</svg>

Modern CSS Solutions Available Today

Today's CSS provides powerful tools for responsive typography that don't require JavaScript. From character units to container queries, these techniques offer better performance and cleaner code for professional web development.

Character Units for Line Length

The ch unit represents the width of the '0' character in the current font, making it ideal for setting readable line lengths. WCAG guidelines recommend limiting line length to 80 characters for readability, with 50-75 characters being optimal.

ch-units.css
1.measure {2 width: 65ch;3 max-width: 100%;4}

The clamp() Function

CSS's clamp() function enables fluid typography that scales between minimum and maximum values while adapting to the viewport. For text fitting, it helps constrain font sizes so they don't become too small or too large.

clamp-typography.css
1.responsive-text {2 font-size: clamp(1rem, 5vw + 0.5rem, 3rem);3}

Container Query Units

Container query length units (cqi, cqw) are relative to the dimensions of a container query container, enabling truly component-level responsive typography.

container-units.css
1.card {2 container-type: inline-size;3}4 5.headline {6 font-size: clamp(1.5rem, 10cqi, 3rem);7}

The CSS Fit-to-Width Technique (Pure CSS)

Roman Komarov developed an innovative pure CSS technique that achieves text fitting without JavaScript, using container query length units, registered custom properties, and mathematical functions.

How the Technique Works

The approach involves several clever CSS features working together:

  1. Text duplication - The visible text is paired with a hidden duplicate for measurement
  2. Container setup - A flex container creates a "remaining space" container alongside the text
  3. Captured custom properties - Registered properties capture computed values for calculations
  4. Ratio calculation - The tan(atan2()) technique performs division to get a scaling ratio
  5. Font-size application - The calculated ratio is applied to font-size with appropriate clamping
fit-to-width.css
1@property --available-space {2 syntax: '<length>';3 initial-value: 0px;4}5 6.text-fit {7 display: flex;8 container-type: inline-size;9}10 11.text-fit > :not([aria-hidden]) {12 flex-grow: 1;13 --available-space: 100cqi;14}15 16.text-fit > :not([aria-hidden]) > * {17 --captured-length: 100cqi;18 --ratio: tan(atan2(19 var(--available-space),20 var(--available-space) - var(--captured-length)21 ));22 font-size: clamp(1em, 1em * var(--ratio), 23 var(--max-font-size, infinity * 1px));24 white-space: nowrap;25}

The Future: Native CSS Text Fitting

The text-grow and text-shrink Properties

The Chrome team has prototyped native CSS properties for text fitting: text-grow and text-shrink. These properties will enable simple, performant text fitting without JavaScript or complex CSS techniques.

Proposed Syntax

Fit targets:

  • per-line - Each line grows/shrinks independently to fit the container
  • consistent - All lines scale by the same factor based on the shortest (for grow) or longest (for shrink) line

Fit methods:

  • scale - Scale glyphs proportionally (doesn't change font-size)
  • scale-inline - Scale only horizontally
  • font-size - Adjust the actual font-size
  • letter-spacing - Adjust letter spacing instead
text-grow-syntax.css
1/* Syntax */2text-grow: <fit-target> <fit-method>? <length>?;3text-shrink: <fit-target> <fit-method>? <length>?;4 5/* Examples */6.headline {7 text-grow: per-line scale;8}9 10.subtitle {11 text-shrink: consistent scale-inline 0.5em;12}

Accessibility Considerations

The CSSWG proposal acknowledges accessibility concerns, particularly around user font size preferences and zoom functionality. Current discussions include ensuring that enlarged text doesn't break the fitting behavior. Implementing accessible typography is also a key component of technical SEO services, as search engines prioritize websites that serve all users effectively.

Performance Best Practices

Minimizing Reflow and Repaint

Text fitting techniques can cause layout shifts if not implemented carefully.

Avoid JavaScript on resize

CSS-based solutions prevent resize event handler accumulation

Use CSS containment

Container queries provide intrinsic sizing without triggering full layout recalculations

Set constraints early

Define min and max font sizes to prevent extreme values

Consider content-visibility

For below-the-fold text fitting, this can improve rendering performance

Initialize properly

Reserve space for maximum expected text size to reduce CLS

Practical Implementation Guide

Choosing the Right Approach

Choosing the right text fitting approach
ApproachBest ForBrowser SupportComplexity
JavaScript librariesLegacy projects, complex requirementsAllLow
SVG techniqueStatic content, email compatibilityAllMedium
clamp() with vwSimple responsive typographyModernLow
Container query unitsComponent-based responsive textModernMedium
Fit-to-width CSS hackProgressive enhancementModernHigh
text-grow (future)Future-proof implementationsPrototypeLow

Quick Start: Simple Text Fitting with clamp()

quick-start.css
1.text-fit {2 container-type: inline-size;3 container-name: text-container;4}5 6.text-fit-content {7 font-size: clamp(1.5rem, 8cqi, 4rem);8 white-space: nowrap;9}

Fallback Strategies

For older browsers or progressive enhancement, use feature detection via @supports.

fallback.css
1.text-fit {2 /* Fallback for browsers without container queries */3 font-size: 2rem;4}5 6@supports (container-type: inline-size) {7 .text-fit {8 container-type: inline-size;9 font-size: clamp(1.5rem, 8cqi, 3rem);10 }11}

Conclusion

Text fitting in CSS has evolved from requiring JavaScript libraries to becoming a native CSS feature. Today's developers can choose from practical modern solutions like container query units with clamp(), while looking forward to the simplicity of text-grow and text-shrink.

For immediate projects, the container query approach provides the best balance of capability and browser support. The key considerations remain accessibility, performance, and appropriate use cases. Text fitting enhances visual design but should never compromise readability or user preferences. Implementing these responsive typography techniques is a fundamental skill for any web development project, ensuring your designs adapt beautifully across all devices and screen sizes.