CodeBlanks Logo Icon CodeBlanks

SVG icons

CSS course · Intermediate · Lesson 92/98

Learn an icon system with SVG.

SVG as icons

The modern way to build an icon set is to embed each icon as inline SVG in the HTML. The icon is used like a font glyph but with vector quality, not pixels.

The benefits: icons change color instantly with fill and stroke, respond to hover, and add no extra file request. You can also add accessibility attributes like aria-hidden for screen readers.

Building an icon system

An icon system works with consistent class names and shared styles. You give each icon class="icon"; a common size is set with .icon { width: 1.5em; height: 1.5em }. Icons then snap to the text baseline automatically.

For color, if you use fill: currentColor, the icons follow the parent's color. Change the color in one place; the whole icon set updates.

Exercise Set up the icon system

Inside the .icon selector, write three declarations: width: 1.5em, height: 1.5em and fill: currentColor. All icons become the same size and follow the text color.

Show example solution
open the .icon selector; write width: 1.5em; height: 1.5em; fill: currentColor; inside.
Example solution:
.icon {
  width: 1.5em;
  height: 1.5em;
  fill: currentColor;
}

Accessible icons

Decorative icons should be hidden from screen readers; otherwise they get read out for no reason. You add the aria-hidden="true" attribute to the SVG.

Meaningful icons take a different path: you write the icon's name in a <title> element and mark it as an image with role="img". The screen reader then reads the icon correctly.

Exercise Highlight the icon on hover

Inside .icon:hover, write two declarations: set fill to #dc2626 and stroke-width to 2. On hover both color and edge change.

Show example solution
open .icon:hover; write fill: #dc2626; and stroke-width: 2; inside.
Example solution:
.icon:hover {
  fill: #dc2626;
  stroke-width: 2;
}

Test yourself

  1. What is an advantage of inline SVG icons?

    • Takes only a single color
    • Downloads a file each time
    • Changes color with CSS
    • Opens outside the browser
    Show answer

    Changes color with CSS — Correct! CSS reaches every element of inline SVG; color changes instantly.

  2. Give the icon class a common size

    .icon {
      width: 1.5em;
      ____: 1.5em;
    }
    Show answer
    .icon {
      width: 1.5em;
      height: 1.5em;
    }

All lessons in Intermediate