All examples By author By category About

veltman

Responsive SVG with sticky text

Keeping text size sticky while making an SVG responsive with viewBox.

  1. Set the SVG's viewBox to its original width and height, and its width to 100%, so it fills its container.
  2. On resize, find out the SVG's new width.
  3. Update the SVG's height to preserve the aspect ratio.
  4. 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