Scaling SVGs with Font Size Using EM Units

Sizing scalable vector graphics (SVGs) using em units is an effective technique for creating responsive icons and inline graphics that dynamically adapt to the size of surrounding text. This article explains the CSS mechanics behind the em unit, how it works in tandem with the SVG viewBox attribute, and why this combination ensures perfectly proportional visual scaling across varied design contexts.

Understanding the em Unit in CSS

The em unit is a relative CSS measurement based on the computed font-size of the current element or its nearest parent. For example, if a paragraph has a font-size of 16px, 1em inside that paragraph equals 16px. If the paragraph’s font-size increases to 24px, 1em automatically recalculates to 24px.

Because em is directly tied to typography metrics, applying it to non-text elements makes those elements react instantly to changes in typography.

How SVGs Utilize em Dimensions

To make an SVG scale proportionally with text, two key configurations are required: an internal coordinate system and external CSS dimensions.

  1. The viewBox Attribute: The SVG must include a viewBox attribute (e.g., viewBox="0 0 24 24"). The viewBox defines the internal aspect ratio and coordinate space of the vector artwork. This ensures that the vector paths scale cleanly without distortion when the outer container changes size.
  2. Dimensioning with em: By setting the SVG’s width and height to 1em via inline attributes or CSS, the outer container of the SVG assumes the exact height and width of the current font size.
svg.icon {
  width: 1em;
  height: 1em;
  fill: currentColor;
}

Proportional Scaling in Practice

When an SVG icon is sized to 1em by 1em and placed inside a button, link, or heading, its physical footprint matches the text scale:

Because the vector paths inside the SVG scale infinitely along the defined viewBox, the graphic retains sharp fidelity and identical relative proportions at every font size.

Advantages of em-Scaled SVGs