Accepted answer

If you want the SVG to scale to fit its parent element, it needs to have a viewBox attribute.

Instead of setting the width and height of your SVG, use those values for the viewBox instead.


.attr("width", width + margin.right + margin.left)
.attr("height", height + + margin.bottom);


.attr("viewBox", [0, 0, (width + margin.right + margin.left),
                        (height + + margin.bottom)].join(' '))

Updated Codepen

You may want to tweak the width and height components of the viewBox if you want, to remove the gap on the right, so it fits more neatly.

Related Query