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

Responsive SVG Charts

Make charts scale properly using viewBox, preserveAspectRatio, and container-based sizing.

Responsive SVG Charts

You'll learn how to make your SVG charts scale gracefully across all screen sizes without distortion or unnecessary scrolling.

What Makes SVG Charts Responsive?

Unlike bitmap images, SVG charts can scale infinitely—but only if you set them up correctly. The key is divorcing the chart's internal coordinate system from its display size. Think of it like a blueprint: the measurements on paper stay the same whether you view it on your phone or project it on a wall.

The viewBox Attribute

The viewBox defines your chart's internal coordinate space as four values: min-x min-y width height. This creates a "window" into your SVG content:

<svg viewBox="0 0 800 400" xmlns="http://www.w3.org/2000/svg">
  <!-- Your chart paths, bars, etc. drawn in 800×400 space -->
</svg>

Now your chart uses an 800×400 coordinate system internally, regardless of how large it displays.

Container-Based Sizing

Remove fixed width and height attributes from the SVG itself. Instead, let CSS control the display size:

.chart-container {
  width: 100%;
  max-width: 1200px;
}

.chart-container svg {
  width: 100%;
  height: auto;
}

The SVG will scale to fill its container while maintaining its aspect ratio defined by the viewBox.

The preserveAspectRatio Property

This controls how the viewBox scales within the SVG viewport. The default xMidYMid meet centers your chart and scales it to fit:

<svg viewBox="0 0 800 400" preserveAspectRatio="xMinYMin meet">

Use none only if you want the chart to stretch and potentially distort—rarely ideal for data visualization.

Key Takeaway: Responsive SVG charts rely on viewBox for internal coordinates, container CSS for display sizing, and preserveAspectRatio to control scaling behavior—together they create charts that look sharp at any size.