SVG Sizing Once And For All

How-To Reference

Today I want to get a grip on sizing SVGs once and for all. I’ve learned about SVGs before but every time I actually use them in code, what I think I know doesn’t have the outcome I expect. So in the next hour I will learn this with the following assumptions & requirements:

  • I can edit the SVG element
  • I will use the SVG markup inline rather than placed as an img
  • I can still style with colors, animations, etc no matter what size it is
  • The SVG is accessible

*Reads her own blog*

Ok turns out I already wrote this! 😂😂😂 So I’ll just make this a simple reference instead for future me…

SVG Checklist

✔ Keep Viewbox, Remove Height & Width

  • This sets the default size to 0 x 0 pixels, so you’ll always have to size them independently.
  • Alternative: Keep height and width, but set them to 100%. Then you MUST always define size in the parent element.
    • This isn’t a good solution for SVGs with inline text.

Ignore the temptation to change the viewbox dimensions. Viewbox handles the height/width ratio of the SVG, not the dimensions of the SVG output on a page. If you change it you’ll just mess up the image, since all of the SVG’s internal elements are drawn in relation to the viewbox.

✔ Add important SVG global styles

svg {
fill: currentColor;
pointer-events: none;
}

The currentColor Fill will give all SVGs the color of their parent containers by default. No pointer events will disable the default tooltip which will otherwise show up on hover.

✔ Use ems for inline text

p svg {
height: 1em;
width: 1em;
}

This will usually keep the SVG in line with text, but it really depends on the font & SVG design. See demo.

✔ Include these attributes on the SVG element for accessibility

  • role="img" or role="text" or role="presentation" depending on the context
    • This ensures screen readers include or ignore the element as intended
    • It also ensures they skip over all of the svg child elements
  • aria-labelledby="title-id description-id"

✔ Always have a <title> as the first child within an <svg> element (plus optional description)

<title id="title-id" lang="en">Useful Title</title>
<desc id="description-id">Useful description</desc>

This is what screen readers will describe, based on the aria-labelledby attribute set above.

Resource List