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


