Styling SVGs with CSS only works in certain conditions

Posted . Visible to the public.

SVG is an acronym for "scalable vector graphics". SVGs should be used whenever an image can be described with vector instructions like "draw a line there" or "fill that space" (they're not suited for photographs and the like). Benefits are the MUCH smaller file size and the crisp and sharp rendering at any scale.

It's a simple, old concept brought to the web – half-heartedly. While actually all browsers pretend to support SVG Show archive.org snapshot , some barely complex use cases get you beyond common browser support.

In the basic scenario, you use SVGs instead of PNG or JPG graphics:

<img src="example.svg" />

The big advantage over other image/icon formats is: SVGs can actually be styled with CSS. Changing size or color, even coloring different parts individually. However, this has limitations:

Issues

Only inline SVGs can be styled with CSS
: You need an <svg> and child tags in your HTML to apply CSS (which kind of makes sense). Rendering SVGs as images (<img src="...svg" />) or <object>s rules CSS out.

IE does not support <svg> with <use> tags
: Referencing SVG definitions is a great way to have DRY inline SVGs, and even allows for using "SVG sprites". However: they're not supported in IE 11-. If you need to support IE, either stick with SVGs as plain image (PNG, JPG, ...) replacements or render ALL SVGs inline. However, this has another drawback:

Inline SVGs bloat your HTML's size
: If you render all SVGs inline, you'll be injecting kilobytes of data into the HTML. This delays downloading your page. It may be ok when there are limited occurrences of SVG images, but you should make sure it stays reasonable. Make sure to optimize your SVGs (see bottom).

Solution

This is where icon fonts come into play. Turn your SVGs into a webfont to deliver crisp and styleable SVGs to the client.

If, for weird reasons, you cannot use icon fonts, your best bet is still to render your SVGs inline. Here's some CSS that may help you render SVG icons like an icon font would:

svg
  width: auto
  height: 1.025em
  vertical-align: -0.075em

  &, path
    fill: currentColor

Notes

SVGs can be used in a sprite just like images

However, this again limits them to image powers. No CSS possible.

SVGs are XML

Implied: there can be loads of unneeded data. The SVG Optimizer squashes it and can shrink SVGs to a fraction of their original size.

Read on

Dominik Schöler
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2016-10-10 15:01)