liveBook · Manning

Viewbox attribute

As explained in D3.js in Action, Third Edition

The viewBox attribute defines the coordinate-system origin, width, and height used to map SVG content into its viewport.

The SVG viewBox attribute defines the coordinate area used to display an SVG. Its four numbers are the horizontal origin, vertical origin, width, and height, in that order. For example, viewBox="0 0 900 300" starts at (0, 0) and defines an area 900 units wide by 300 units high. The width and height establish a 900:300 aspect ratio. section 1.2.2

Make a gallery of SVG shapes responsive

Start with <svg width="900" height="300">. Those fixed dimensions do not adapt to the browser window. Changing only the width to 100% makes it flexible but loses the original aspect ratio. Instead, remove both dimensions and use <svg viewBox="0 0 900 300">. Resize the window: the SVG adapts while keeping its proportions. To stop it growing too large, wrap it in a div styled with width:100%; max-width:1200px; margin:0 auto. section 1.2.2

The origin does not have to be (0, 0): changing its first two numbers changes which portion of the SVG is visible. Keep the width and height in proportion to the layout you want to display. section 1.2.2

Set viewBox with D3

For a bar chart, select its responsive container, append an SVG, and set .attr("viewBox", "0 0 1200 1600"). Here 1200 matches the container’s maximum width, while 1600 is an initial height that can be adjusted. Spell viewBox with a capital B: the attribute name is case-sensitive. section 2.5

d3.select(".responsive-svg-container")
  .append("svg")
    .attr("viewBox", "0 0 1200 1600");

The complete D3 selection-and-append chain shows where to set viewBox when creating the bar chart’s SVG. section 2.5

How D3.js in Action, Third Edition covers it

How deep it goes
Defines all four values and walks through fixed, percentage-width, and viewBox sizing without exploring other SVG fitting controls.
Examples
Uses a 900-by-300 SVG shapes gallery and a bar chart with viewBox="0 0 1200 1600".
What it assumes
Starts with an SVG element and teaches its sizing and viewBox values directly; the D3 example uses selections and attr().
What you can do after
Apply it via SVG markup or D3’s attr() method to preserve proportions while an SVG adapts to its container.
How it connects
Connects SVG coordinate systems and aspect ratios to responsive containers and D3 attribute setting.

Also explained in

Compare how 3 books explain viewbox attribute →

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.