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.
- The
viewBoxAttribute: The SVG must include aviewBoxattribute (e.g.,viewBox="0 0 24 24"). TheviewBoxdefines 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. - Dimensioning with
em: By setting the SVG’swidthandheightto1emvia 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:
- Inside an
<h2>heading (font-size: 32px): The icon renders at32px × 32px. - Inside body copy (
font-size: 16px): The same icon renders at16px × 16px. - Inside small caption text
(
font-size: 12px): The icon renders at12px × 12px.
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
- Component Reusability: A single icon definition can be used across navigation bars, headers, body copy, and footers without requiring specific size modifier classes for each location.
- Responsive Adaptability: When text scales through
responsive typography systems (such as using
clamp()or media queries), the associated icons scale seamlessly in tandem without additional CSS rules. - Visual Harmony: Using
1emensures that icons maintain optical alignment and visual balance alongside adjacent alphanumeric characters. Pairing this withfill: currentColorallows the SVG to inherit both the size and the color of surrounding text simultaneously.