Matthew Conlen is working as a graphics editor at the New York Times and completing a computer science Ph.D at the University of Washington.
Writing
Easy responsive SVGs with ViewBox
January, 2016

The viewBox attribute of SVGs is underutilized. While it has been written about before, it seems useful enough to warrant another post.

There is a very simple technique that many interactive d3 creations can immediately benefit from. The viewBox attribute defines how an SVG scales up. To take advantage of it, use viewBox to define the aspect ratio for your graphic, and allow the browser to flexibly decide what size it should be displayed on a reader's screen.

Consider the following two examples using d3.js. In both I use the following code to render a checkerboard pattern after creating an svg element.


without viewbox

Full code: https://gist.github.com/mathisonian/d5edeae8c805130a09e1


with viewbox (try resizing your browser window! this will always resize to fill its parent)

Full code: https://gist.github.com/mathisonian/faceca3e51ecf73b3eb1


The only difference in the code is at the very beginning where I create the SVG. In example 1 I explicitly set the size to 202 pixels, while in the second I use viewbox. Note all subsequent code after creating the SVG is identical.

The first example shows how the SVG behaves with an explicit width and height set. The second shows how it behaves using viewBox to resize dynamically. Try resizing your browser window to see the behavior of each.

Even better is that all interactivity (for example, d3 click and mouseenter events) works as expected. See below for a responsively sized example that responds to these events:

Full code: https://gist.github.com/mathisonian/b161bfed68a177591e1d


This technique can work on shapes with a different aspect ratio as well. Consider the following code to draw a rectangle with a 16:9 aspect ratio. Notice how the rectangle behaves when resizing the browser. It is set up in css to fill 75% of its parent's width.


Live example:


Full code: https://gist.github.com/mathisonian/42a4adf305916a9174f8



Do note, this is just the tip of the iceberg in terms of what you can do with the SVG coordinate system. To learn more follow the links below.


Further reading: