liveBook · Manning

Responsive SVG

As explained in D3.js in Action, Third Edition

A responsive SVG is an SVG graphic whose rendered size adapts to its containing element while preserving its intended coordinate relationships and aspect ratio.

A responsive SVG adapts to the space provided by its parent while keeping a stable internal drawing space. Treat the SVG as a whiteboard: shapes use coordinates inside that whiteboard, while the browser scales the result for the available layout width. section 1.2.2 section 4.4

Define the drawing coordinate system with `viewBox="0 0 900 300"`, then omit `width` and `height`. The last two viewBox values establish the intended drawing width and height; without fixed rendered dimensions, the container can adapt to its parent and preserve its aspect ratio. Put the SVG in a fluid wrapper when the page needs a maximum content width. section 1.2.2 section 4.4

A fluid shape gallery

Wrap a 900-by-300 drawing space in a container that is `width:100%`, capped with `max-width:1200px`, and center it with automatic margins. Inside, position lines, rectangles, circles, ellipses, paths, and labels using the fixed viewBox coordinates. The graphic scales as one coordinated composition rather than requiring every shape position to change. section 1.2.2

For layouts whose chart structure changes with screen width, calculate dimensions reactively instead. Bind the window width, choose a column count at breakpoints, derive each small multiple’s width and height, then derive total SVG height from the number of rows. Render the SVG only after its computed dimensions exist. section 14.4.1

const pieChartWidth = 300;
const pieChartHeight = 300;
const svg = d3.select("#arc")
  .append("svg")
  .attr("viewBox", [0, 0, pieChartWidth, pieChartHeight]);

This compact D3 setup appends an SVG with a 300-by-300 viewBox and no fixed width or height, allowing its parent to control the rendered size. section 4.4

How D3.js in Action, Third Edition covers it

How deep it goes
Explains viewBox-based resizing and develops reactive width, height, rows, and columns for a responsive SVG grid.
Examples
Builds a gallery of SVG shapes, a D3 arc container, and a breakpoint-driven grid of yearly small multiples.
What it assumes
Introduces SVG containers and attributes from zero while using basic HTML, CSS, browser inspection, and JavaScript in implementations.
What you can do after
Build it from scratch with a viewBox-based container or reactive dimensions that follow screen-width breakpoints.
How it connects
Connects SVG containers and viewBox coordinates with D3 selections, responsive layouts, Flexbox grids, and small multiples.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.