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;
}

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:

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;
}