As mentioned before, recently I’ve been working on my SVG skills.

A while back I read a great SVG icon tip from Andy Bell which I’d been meaning to try and finally did so today.

Andy recommended setting the width and height of icons to 1em then using font-size to further tweak them.

Here’s a pen I created this morning to test-drive the technique.

See the Pen Control SVG icon size with font-size and match colour to parent text by Laurence Hughes (@fuzzylogicx) on CodePen.

And here’s some key points I’ve noted:

  • By applying width and height of 1em to our icon it is predictably sized by default.
  • It can now have its size further tweaked in CSS using font-size, for example with ems (where 1em = the font-size of the parent anchor element).
  • This technique requires the “viewbox” attribute being present on the svg.
  • Apply the width and height =1em as inline attributes on the svg. We could apply them using CSS, however the inline approach avoids potentially massive icons showing in cases where CSS doesn’t load.
  • To get the colour matching, apply fill="currentColor" as an inline attribute on the svg’s path.
  • Now, when you apply a hover colour to the anchor in CSS, the icon will just pick that up. Nice!
  • Applying inline-flex to the anchor makes the vertical-alignment of text and icon easier.
  • Add aria-hidden on the icon because it’s mainly decorative so we don’t want it read out by screen readers.