Understanding SVG viewBox Letterboxing and Slicing

This article explains how Scalable Vector Graphics (SVG) handle mismatched aspect ratios between the rendering viewport and the internal viewBox. When these dimensions do not match, the preserveAspectRatio attribute dictates whether the graphic scales uniformly to fit entirely inside the container (letterboxing) or scales to cover the entire container (slicing). Understanding this calculation ensures precise visual rendering and responsive behavior across different screen sizes.

The Viewport vs. The viewBox

An SVG utilizes two coordinate systems: 1. The Viewport: The outer box defined by the SVG’s width and height attributes (or computed CSS dimensions). 2. The viewBox: The internal coordinate space defined by viewBox="min-x min-y width height".

When the aspect ratio of the viewport does not equal the aspect ratio of the viewBox, SVG cannot scale the width and height equally without either distorting the graphic, clipping parts of it, or leaving empty space.

The preserveAspectRatio Attribute

Uniform scaling is controlled by the preserveAspectRatio attribute, which takes two values: an alignment specifier and an optional meetOrSlice parameter.

preserveAspectRatio="<align> [<meetOrSlice>]"

The meetOrSlice parameter defaults to meet if omitted.

How Letterboxing Works (meet)

The meet option scales the entire viewBox up or down until it reaches the boundaries of the viewport while preserving its original aspect ratio.

How Slicing Works (slice)

The slice option scales the viewBox uniformly until it completely covers the entire viewport area.

Practical Comparison