SVG Sizing: em vs px Units Explained

Sizing Scalable Vector Graphics (SVG) correctly is essential for creating responsive, accessible, and visually consistent web layouts. When defining the width and height of an SVG, choosing between em units and px (pixel) units determines whether the graphic remains fixed in size or scales dynamically with surrounding typography. While px units provide predictable, absolute dimensions, em units tie the graphic’s dimensions directly to the parent element’s font size.

What Are px Units in SVG Sizing?

Pixel (px) units are absolute units in CSS and HTML. When you set an SVG’s dimensions using pixels (e.g., width="24px" or width: 24px;), the graphic renders at that exact size regardless of the context, surrounding text, or the user’s browser font preferences.

What Are em Units in SVG Sizing?

The em unit is a relative unit calculated based on the font-size of the element or its nearest parent. Setting an SVG’s dimensions to 1em by 1em means the graphic will automatically match the exact size of the surrounding text.

Key Differences Between em and px

Feature px Units em Units
Measurement Type Absolute Relative to parent font-size
Text-Scaling Behavior Static; does not change with text Dynamic; scales proportionally with text
Accessibility Ignores user-defined text size overrides Adapts automatically to text resizing
Maintenance Requires explicit media queries to resize Inherits sizing rules defined for typography

The Role of the viewBox Attribute

Regardless of whether you choose px or em units for the outer dimensions, an SVG must include a properly configured viewBox attribute. The viewBox defines the internal coordinate system and aspect ratio of the graphic. When the outer container size is altered—whether through fixed pixels or fluid em scaling—the viewBox ensures the internal vector paths scale smoothly without distortion or clipping.