Keeping text size sticky while making an SVG responsive with viewBox
.
- Set the SVG's
viewBox
to its original width and height, and its width to 100%, so it fills its container. - On resize, find out the SVG's new width.
- Update the SVG's height to preserve the aspect ratio.
- Use
transform
to scale up the text by the inverse. For example, if the new width is 2/3 of the original, make the text 3/2 scale.
Instead of keeping the text size fixed, you could constrain it to some other range so that it shrinks but more slowly than the rest of the SVG. For example:
var textScaleFactor = d3.scale.linear()
.domain([300,600]) // expected limits of SVG width
.range([1.5,1]); // when SVG is 1/2 width, text will be 2/3 size
See also: Hannah Fairfield's connected scatterplot on gas prices