CSS with SVG: Real World Usage – SitePoint

SVG is a lightweight vector image format that’s used to display a variety of graphics on the Web and other environments with support for interactivity and animation. In this article, we’ll explore the various ways to use CSS with SVG, and ways to include SVGs in a web page and manipulate them.
The Scalable Vector Graphic (SVG) format has been an open standard since 1999, but browser usage became practical in 2011 following the release of Internet Explorer 9. Today, SVG is well supported across all browsers, although more advanced features can vary.
SVG Benefits
Bitmap image formats such as WebP, PNG, JPG, and GIF define the color of individual pixels. A 100 × 100 PNG image requires 10,000 pixels. Each pixel requires four bytes for red, green, blue and transparency, so the resulting file is 40,000 bytes (plus a little more for metadata). Compression is applied to reduce the file size: PNG and GIF use ZIP-like lossless compression, while JPG is lossy and removes less noticeable details (WebP can use either method).
Bitmaps are ideal for photographs and more complex images, but definition is lost as images are enlarged.
SVGs are vector images defined in XML. Points, lines, curves, paths, ellipses, rectangles, text, etc. are drawn on an SVG canvas. For example:

The viewBox defines a co-ordinate space. In this example, an 800 × 600 area starting at position 0,0 has a yellow circle with a red border and a 250 unit radius drawn in the center:

These are the benefits of vectors over bitmaps:
the SVG above uses fewer than 150 bytes, which is considerably smaller than an equivalent PNG or JPG
SVG backgrounds are transparent by default
the image can scale to any size without losing quality
SVG code/elements can be generated and manipulated on the server (using any language) or browser (using CSS and JavaScript)
in terms of accessibility and SEO, text and drawing elements are machine and human-readable.
SVG images are ideal for logos, charts, icons, and simpler diagrams. Only photographs are generally impractical, although SVGs have been used for lazy-loading placeholders.

It’s useful to understand the basics of SVG drawing, but you’ll soon want to create more complex shapes with an editor that can generate the code. Options include:
Each tool has different strengths, and you’ll get differing results for seemingly identical images. In general, more complex images require more complex software.
The resulting code can usually be simplified and minimized further using SVGO (plugins are available for most build tools), or Jake Archibold’s SVGOMG interactive tool.
SVGs as Static Images
When used within an HTML tag or CSS background-url, SVGs act identically to bitmaps:

.myelement {
background-image: url(“mybackground.svg”);

The browser will disable any scripts, links, and other interactive features embedded into the SVG file. You can manipulate that SVG using CSS in an identical way to other images using transform, filters, etc. The results are often superior to bitmaps because SVGs can be infinitely scaled.
CSS Inlined SVG Backgrounds
An SVG can be inlined directly in CSS code as a background image. This can be ideal for smaller, reusable icons and avoids additional HTTP requests. For example:
.mysvgbackground {
background: url(‘data:image/svg+xml;utf8,‘) center center no-repeat;

Standard UTF-8 text encoding (rather than base64) can be used, so it’s easier to edit the SVG image if necessary.
The process is usually more practical using a tool such as the PostCSS assets plugin.
CSS with SVG: Responsive SVG Images
When creating a responsive website, images are often sized to the width of their container or the image itself (whichever is smaller). This is achieved in CSS using:
img {
display: block;
max-width: 100%;
height: auto;

However, an SVG used in an tag may have no implicit dimensions. You might discover the max-width is calculated as zero and the image disappears entirely. To fix the problem, ensure a default width and height is defined in the tag:

HTML-inlined SVG Images SVGs can be placed directly into HTML markup. The image then becomes part of the DOM and can be manipulated using CSS and JavaScript:

SVG is inlined directly into the HTML:

The SVG is now part of the DOM.

In this case, width or height attributes are not necessary because the dimensions can be directly controlled. For example:
#invader {
display: block;
width: 200px;
height: auto;

#invader path {
stroke-width: 0;
fill: #080;

However, adding the dimensions ensures the SVG is not sized inappropriately when CSS is not applied.

See the Pen HTML-Inlined SVG by SitePoint (@SitePoint)on CodePen.

SVG elements such as paths, circles, rectangles etc. can be targeted by CSS selectors and have the styling modified using standard SVG attributes as CSS properties. For example:

circle {
stroke-width: 20;
stroke: #f00;
fill: #ff0;

This overrides any attributes defined within the SVG because the CSS has a higher specificity. SVG CSS styling offers several benefits:
attribute-based styling can be removed from the SVG entirely to reduce the page weight
CSS styling can be reused across any number of SVGs on any number of pages
the whole SVG or individual elements of the image can have CSS effects applied using :hover, transition, animation etc.
SVG Sprites
A single SVG file can contain any number of separate images. For example, this folders.svg file contains folder icons generated by IcoMoon. Each is contained within a separate container with an ID which can be targeted:
folder open plus minus download upload

The SVG file can be referenced as an external, cached resource in an HTML page. For example, here’s how to show the folder icon at #icon-folder:

And here’s how to style it with CSS:
svg.folder { fill: #f7d674; }

The method has a couple of drawbacks:
It fails in IE.
CSS styling only applies to the element containing the . The fill here makes every element of the icon the same color. To solve these issues, the SVG sprite can be embedded within page HTML then hidden using display: none or similar techniques. An individual icon can be placed by referencing the ID:

See the Pen SVG sprites by SitePoint (@SitePoint)on CodePen.

This works in all modern browsers including IE9+ and it becomes possible to style individual elements within each icon using CSS.
Unfortunately, the SVG set is no longer cached and must be reproduced on every page where an icon is required. The solution (to this solution!) is to load the SVG using Ajax — which is then cached — and inject it into the page. The IcoMoon download provides a JavaScript library, or you could use SVG for Everybody.
SVG Effects on HTML Content
SVG has long supported:
masks: altering the visibility of parts of an element
clipping: removing segments of an element so a standard regular box becomes any other shape
filters: graphical effects such as blurring, brightness, shadows, etc.
These effects have been ported to the CSS mask, clip-path, and filter properties. However, it’s still possible to target an SVG selector:

.myelement {
clip-path: url(#clip);

This references an effect within an HTML-embedded SVG:

It produces effects such as clipped text with an image or gradient background:

See the Pen SVG clipping by SitePoint (@SitePoint)on CodePen.

Portable SVGs
Finally, a standalone SVG file can contain text, CSS, JavaScript, bitmap images, and even base64-encoded fonts! Anything outside the realms of XML should be contained within Consider the following invader.svg file. It defines CSS styling with hover effects and a JavaScript animation which changes the viewBox between two states:

When referenced in an HTML or CSS background, the SVG becomes a static image of the initial state (in essence, the first animation frame):

However, open the image in its own browser tab and all the effects will return.
This could be useful for distributing images, demonstrations, or small documents which require some embedded interactivity.
Sophisticated SVGs
SVGs offer a wide range of technical possibilities — both within and outside of web pages. It becomes possible to style and animate the whole SVG image or individual drawing elements using CSS and/or JavaScript.
This article describes ways to manipulate SVG images, but they’re regularly used for smaller visual enhancements, such as:
form focus highlights and validation
turning a hamburger menu into a an X close icon
lava-lamp–like morphing.
Despite the age of SVG technology, web developers are still discovering interesting ways to transform boring block-based pages with subtle effects through using CSS and SVG images. Let me know on Twitter if you create any good demonstrations.

Coded at

Share your love

Leave a Reply