Today I wrote an article for the Praxis blog outlining four free charting/visualization tools and showing examples of visualizations created with those tools. One outputs SVGs, but they are a fixed size. But since SVGs are just code, I figured I could make it responsive.
First I tried the old responsive image trick:
width: 100%; height: auto; – This resulted in the SVG scaling, but only the top 10% was visible.
After some Googling, I came across this article: How to Scale SVG on CSS Tricks. Here I learned about the
viewbox attribute. The viewBox does many things:
- It defines the aspect ratio of the image.
- It defines how all the lengths and coordinates used inside the SVG should be scaled to fit the total space available.
- It defines the origin of the SVG coordinate system, the point where x=0 and y=0.
My original SVG was 848px by 500px. So, I set
viewbox="0 0 848 500" and
width=100% and removed the
This led to a nice scalable SVG: