Course contentsShow
← Web Development
Lesson 2655 of 2,98247. Data VisualizationFree lesson

Responsive SVG Viewbox and Aspect Ratios

Learn how to make SVG charts scale fluidly using viewBox and preserveAspectRatio for all screen sizes.

Responsive SVG Viewbox and Aspect Ratios

You'll learn how to make SVG charts scale fluidly across all screen sizes using viewBox and preserveAspectRatio.

Why SVG Charts Need Special Scaling

Unlike regular images, SVG is vector-based and infinitely scalable—but only if you configure it correctly. Without proper setup, your beautiful chart might get cropped on mobile or stretched awkwardly on ultrawide displays.

The viewBox Attribute

Think of viewBox as defining a "virtual canvas" for your SVG. It has four values: min-x min-y width height. This tells the browser: "My drawing uses this coordinate system, now fit it into whatever space you have."

<svg viewBox="0 0 800 400" width="100%">
  <!-- Your chart elements here -->
</svg>

Here, viewBox="0 0 800 400" means your chart was designed in an 800×400 coordinate space. Setting width="100%" (and omitting a fixed height) lets it scale responsively while maintaining proportions.

The preserveAspectRatio Attribute

This controls how the scaling happens. The default xMidYMid meet centers your chart and scales it to fit entirely within the container (like CSS object-fit: contain).

<svg viewBox="0 0 800 400" preserveAspectRatio="xMinYMin meet">
  • xMinYMin: Align to top-left
  • xMidYMid: Center (default)
  • meet: Scale to fit inside (letterbox if needed)
  • slice: Scale to fill (crop if needed)

Common Responsive Pattern

<svg viewBox="0 0 800 400" width="100%" height="auto" preserveAspectRatio="xMidYMid meet">
  <!-- Chart uses 0-800 x-coords and 0-400 y-coords -->
</svg>

This creates a chart that fills its container's width while maintaining a 2:1 aspect ratio.

Key Takeaway: Use viewBox to define your chart's internal coordinate system and preserveAspectRatio to control scaling behavior—together they make SVG visualizations truly responsive without media queries or JavaScript.