Introduction to scaling inline SVG (Scalar Vector Graphics) images

Dec 16, 2020


Ideas for the content of this website's 404 page popped in and out of my head for a couple days. I finally settled on a maze that had been followed to a dead-end. A quick search led to , where you can generate mazes of any size and complexity for free as long as you aren't using it commercially. The maze (with its solution) can be downloaded as an SVG (Scalar Vector Graphics) format, which is a standard format for graphics that I really like because it is text-based and looks good at any zoom level. I changed the "solution" part of the file to go to a dead-end, and made it the complementary color of the site toolbar in homage to my alma mater.

The as-downloaded SVG maze had a set height and width of 324:

<svg width="324" height="324" version="1.1" xmlns="http://www.w3.org/2000/svg">
  <title>20 by 20 orthogonal maze</title>
  <desc>20 by 20 orthogonal maze generated by The Maze Generator Website (http://www.mazegenerator.net/).</desc>
  <g fill="none" stroke="#000000" stroke-width="2" stroke-linecap="square">
    <line x1="2" y1="2" x2="146" y2="2" />
    <line x1="162" y1="2" x2="322" y2="2" />
    ...
    ...

This maze is an SVG with internal dimensions of 324 x 324. If you look at the <line /> x and y units, they are drawing lines within that 324 x 324 box. But we need a way to make the SVG scale to different image sizes - sometimes we will want it to fill a 600 x 600px area on the screen, sometimes 250 x 250px. The hardcoded width and height SVG attributes in the above code prevent scaling; this SVG will always be 324 x 324px.

There is an SVG attribute that does what we want: viewBox. I learned about it in an article by Amelia Bellamy-Royds on CSS Tricks called How to Scale SVG. viewBox takes the dimensions of your SVG code and scales it to the available area on your website. The replacement we are looking for is:

<svg viewBox="0 0 324 324" version="1.1" xmlns="http://www.w3.org/2000/svg">

The first two numbers ("0 0") are the x and y origins, and the second two numbers ("324 324") are the internal SVG x and y dimensions. If your coordinate system origin was in the exact center of your image, you would set viewBox="162 162 324 324", but the origin in SVG is usually in the upper left corner by default. With the 0 0 324 324 replacement, the maze looks good on a phone and takes up the entire container width on desktop. Note that this solution works when you put the <svg> code directly in your HTML - if you enclose your SVG in another tag such as <img> you may need a slightly more complex solution. See the CSS Tricks article for more info.

Happy coding and don't get lost!

20 by 20 orthogonal maze 20 by 20 orthogonal maze generated by The Maze Generator Website (http://www.mazegenerator.net/).