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





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







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:





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:













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: