How to Scale SVG to Parent Container Automatically
Scaling an SVG to seamlessly fit its parent container requires
defining the graphic’s internal coordinate system while removing rigid
dimension constraints. By utilizing the SVG viewBox
attribute, removing hardcoded pixel widths and heights, and applying
standard CSS rules, you can ensure that vector graphics scale fluidly
across any screen size or layout without distorting.
1. Define the viewBox
Attribute
The viewBox attribute is the most critical component for
responsive SVG scaling. It establishes the internal coordinate system
and aspect ratio of the graphic. The syntax consists of four values:
min-x, min-y, width, and
height.
<svg viewBox="0 0 500 300">
<!-- Vector paths go here -->
</svg>The browser uses these numbers to calculate the ratio between the SVG’s internal drawing space and the actual display space on the screen.
2. Remove Absolute Width and Height Attributes
If your <svg> element has fixed width
and height attributes defined in pixels (e.g.,
width="500px"), the browser will prioritize those
dimensions over the parent container’s size. Remove these attributes
entirely, or set them to relative values like 100%.
3. Apply CSS to the SVG
To make the SVG fill the width of its parent element while maintaining its proportion, apply the following CSS rules:
svg {
width: 100%;
height: auto;
display: block;
}width: 100%forces the SVG to expand or shrink to the full width of its parent element.height: autoensures the vertical dimension adjusts proportionally based on theviewBoxaspect ratio.display: blockremoves default inline spacing beneath the element.
If you need the SVG to stretch to both the full width and full height
of a fixed-size container, set both properties to 100%:
svg {
width: 100%;
height: 100%;
}4. Control Aspect
Ratio with preserveAspectRatio
By default, an SVG will scale uniformly to fit within the container
bounds without distorting. You can control this behavior using the
preserveAspectRatio attribute on the
<svg> tag:
- Uniform scaling (default):
preserveAspectRatio="xMidYMid meet"scales the graphic uniformly until it fits entirely inside the container. - Cover container:
preserveAspectRatio="xMidYMid slice"scales the graphic uniformly to completely cover the container, cropping overflow if necessary. - Non-uniform stretch:
preserveAspectRatio="none"disables aspect ratio constraints, stretching the SVG to match the exact width and height of the container.
Complete Example
HTML:
<div class="svg-container">
<svg viewBox="0 0 800 600" preserveAspectRatio="xMidYMid meet">
<circle cx="400" cy="300" r="200" fill="#007acc" />
</svg>
</div>CSS:
.svg-container {
width: 100%;
max-width: 600px;
}
.svg-container svg {
width: 100%;
height: auto;
display: block;
}