SVG Width and Height 100 Percent Explained
Setting width="100%" and height="100%" on a
root SVG element instructs the graphic to expand and completely fill the
dimensions of its parent container. While this enables fluid
responsiveness, the final visual behavior depends heavily on the
presence of the viewBox attribute, the default
preserveAspectRatio rules, and the layout constraints of
the wrapping HTML element.
Sizing Relative to the Parent Container
When an SVG has percentage-based dimensions, it treats its immediate parent element as the reference frame:
- Defined Container Dimensions: If the parent
container has explicit dimensions (e.g.,
width: 400px; height: 300px;), the SVG expands to precisely 400 pixels wide and 300 pixels tall. - Undefined Container Height: If the parent container
calculates its height based on its content (
height: auto), settingheight="100%"can cause the SVG to collapse to zero height or create layout rendering loops, depending on the browser.
The Critical Role of the
viewBox
The presence of a viewBox determines how the internal
artwork scales within the 100% boundaries:
- With a
viewBox: The internal coordinate system scales automatically. The SVG maintains its internal proportion while expanding to fill the container, preventing the graphic from becoming distorted or clipped. - Without a
viewBox: The internal coordinate system remains fixed in pixel units. If the container expands beyond the internal graphic’s original size, extra empty space appears. If the container shrinks, the graphic gets clipped at the boundaries.
Aspect Ratio and Letterboxing
By default, SVG elements have an implicit
preserveAspectRatio="xMidYMid meet" rule. When
width="100%" and height="100%" force the SVG
into a container with a different aspect ratio than its
viewBox:
- The graphic will scale uniformly until it hits the nearest boundary (width or height).
- The graphic centers itself within the remaining space, resulting in “letterboxing” (empty space on the top/bottom or left/right), rather than stretching or distorting the artwork.
CSS Precedence and Defaults
Attributes defined directly on the SVG element act as presentational
attributes. If external CSS specifies different dimensions (such as
svg { width: 50%; }), the CSS rules will override the
inline width="100%" and height="100%"
declarations. However, leaving the 100% attributes on the root element
provides a reliable fallback for environments where external stylesheets
fail to load or are unsupported.