Quiz

Are you familiar with styling SVG?

Topics
CSS

TL;DR

Inline SVG participates in the document's CSS cascade, so shapes can be styled with properties such as fill, stroke, and color, including states like :hover. Presentation attributes such as fill="red" have low cascade priority and can be overridden by CSS, while a style attribute has inline-style priority. An SVG loaded through <img> is a separate document and cannot normally be styled from the page's stylesheet.

<button class="icon-button" type="button">
<svg class="icon" viewBox="0 0 24 24" aria-hidden="true">
<path d="M5 12h14M12 5l7 7-7 7" />
</svg>
Continue
</button>
.icon {
width: 1.25em;
fill: none;
stroke: currentColor;
stroke-width: 2;
}

Are you familiar with styling SVG?

SVG is an XML-based vector format. How it can be styled depends on how it is embedded.

Inline SVG

An inline <svg> is part of the page's DOM. CSS can target its elements, inherit values, use custom properties, and react to states on the SVG or its ancestors. currentColor is especially useful for icons because it makes SVG paint follow the surrounding text color.

SVG presentation attributes such as fill, stroke, stroke-width, and opacity behave like low-priority author declarations. A stylesheet rule can override them:

<svg
class="status-icon"
viewBox="0 0 20 20"
role="img"
aria-labelledby="status-title">
<title id="status-title">Payment approved</title>
<circle cx="10" cy="10" r="8" fill="green" />
</svg>
.status-icon circle {
fill: var(--status-color, seagreen);
}

Avoid broad selectors such as svg { fill: ... }, which can accidentally fill paths intended to use strokes or their own colors.

External SVG

  • <img src="icon.svg" alt="..."> treats the SVG as an image. Page CSS cannot reach its internal shapes, but the image is cacheable and easy to use.
  • A CSS background-image is appropriate for decoration, not meaningful content, because it has no HTML alternative text.
  • <object> or <iframe> creates a separate document with additional loading, security, and scripting considerations.
  • An external <use> symbol sprite can share icons, but styling behavior depends on how the symbol is authored; prefer currentColor and test the target browsers.

For decorative inline icons, use aria-hidden="true" and ensure the adjacent control has an accessible name. For a standalone informative SVG, provide an accessible name using surrounding HTML or an SVG <title> relationship. Do not put essential text only in generated or decorative graphics.

Further reading

Exercises

Check your understanding
Beta
Check your understanding Exercise 1 of 3
Check your understanding Exercise 1 of 3

Which statements about styling SVG are correct? Select all that apply.