Skip to content
Tutorials Center
My learning

Topics

Lesson 91 of 139 ยท UI Components

Icons in CSS

Add crisp, recolorable icons with inline SVG, SVG sprites and mask-image, size them with em and currentColor, avoid icon-font pitfalls and keep them accessible.

Icons are everywhere in an interface: a magnifying glass in the search box, a trash can on a delete button, a little arrow that says "this opens a menu". Good icons are sharp at any size, match the color of the text around them, line up neatly with labels and make sense to people who can't see them.

This lesson opens the UI Components chapter. You will compare the main ways to put icons on a page (inline SVG, SVG sprites, CSS masks and icon fonts), learn the two tricks that make icons fit any design, 1em sizing and currentColor, and finish with the accessibility rules that every icon needs.

The options at a glance

Technique Recolor with CSS Multi-color Extra requests Notes
Inline <svg> Yes Yes None The most flexible; adds markup to every use
Sprite with <use> Yes Limited One file (or none if inline) Markup stays short; great for many icons
mask-image Yes No One per icon (or data URLs) Pure CSS; the icon is a single color
<img src="icon.svg"> No Yes One per icon Simple, but the colors are fixed in the file
Icon font Yes No One font file Legacy; several accessibility and rendering problems

Today, SVG is the default choice. It's a vector format, so it stays crisp on high-density screens and when zoomed, and it's just text, so it compresses well. SVG Basics in the HTML course explains the markup itself.

Inline SVG and currentColor

The most direct method is to paste the SVG into your HTML. Because it's part of the page, CSS can reach inside it.

The key is currentColor, a keyword that means "the value of the color property". If the icon's fill (or stroke) is currentColor, the icon automatically takes the text color of whatever it sits in:

CSS
.icon {
  width: 1em;
  height: 1em;
  fill: currentColor;
  flex-shrink: 0;
}

The 1em size is the second trick. An em is the current font size, so the icon is exactly as tall as the text's font size. Put it in a large heading and it grows; put it in small print and it shrinks. You never maintain a list of icon sizes.

Icons that follow text color and size

The same star picks up purple, gray, blue and, on hover, red, without a single icon-specific color rule.

Lining icons up with text

Icons next to words often sit a little too high, because inline content aligns to the text baseline, and the bottom of the icon lands there while letters like "g" hang below. Two fixes:

  • The flex way (recommended): wrap the icon and the label in an inline-flex container with align-items: center and a gap, as in the demo. This is how buttons handle icons.
  • The inline way: for an icon in the middle of a sentence, nudge it down with vertical-align: -0.125em. The exact number depends on the icon set, but around one-eighth of an em is typical.

Add flex-shrink: 0 so a long label in a narrow container never squeezes the icon.

Stroke icons

Many icon sets are drawn with lines rather than filled shapes. For those, set fill: none and stroke: currentColor, and choose a stroke-width. If you scale a stroke icon up a lot, the lines scale too; vector-effect: non-scaling-stroke on the paths keeps the line width fixed in screen pixels.

SVG sprites with <symbol> and <use>

Pasting a full <path> every time you need an icon gets repetitive. An SVG sprite defines each icon once as a <symbol> with an id, then shows it anywhere with <use href="#id">:

HTML
<!-- Once, usually at the top of <body> -->
<svg hidden>
  <symbol id="icon-search" viewBox="0 0 24 24">...</symbol>
  <symbol id="icon-trash" viewBox="0 0 24 24">...</symbol>
</svg>

<!-- Every time you need one -->
<svg class="icon"><use href="#icon-search"/></svg>

The <use> element clones the symbol into a hidden copy called a shadow tree. Your page's selectors can't reach inside it, but inherited properties flow in. So fill: currentColor on the outer <svg> (or on the paths, written inside the symbol) still works.

An inline SVG sprite

Each symbol uses currentColor internally, so each button's hover color reaches the icon.

Sprites can also live in a separate file: <use href="/icons.svg#i-search"/>. The browser downloads and caches the file once. One catch: external <use> references must be same-origin. Browsers refuse sprite files from another domain, even with CORS headers, so host the sprite on your own site.

CSS-only icons with mask-image

Sometimes you can't, or don't want to, change the HTML: for example, a decorative arrow on every external link, or icons in generated content. A mask turns any SVG into a stencil. You paint the element with background-color: currentColor, and the mask decides where that color shows through. The full technique is in Clip Paths and Masks; here's the icon recipe:

CSS
.icon-mask {
  display: inline-block;
  width: 1em;
  height: 1em;
  background-color: currentColor;
  -webkit-mask: var(--svg) center / contain no-repeat;
  mask: var(--svg) center / contain no-repeat;
}
An external-link icon added with CSS

The SVG inside the mask can use any solid color (black here). Only its shape matters; the visible color comes from background-color. The attribute selector [href^="http"] picks out absolute URLs, and the pseudo-element adds the icon without extra markup. Because it's generated content, screen readers ignore the icon, which is fine for a decorative hint. If the "opens another site" information matters, add it as visually hidden text too.

Icon fonts, and why they faded

For years, the popular approach was an icon font: a web font whose characters are pictures instead of letters. You'd write <i class="icon-trash"></i>, and CSS would insert a character from the font with ::before. It was easy, and icons took the text color automatically.

Icon fonts have real drawbacks, though:

  • Accessibility. The icons are characters, often in the Unicode "private use" area. Some screen readers announce them as strange symbols or nothing at all.
  • Font failures. If the font is blocked, slow or replaced by a user's own font (common for people with dyslexia or low vision), every icon becomes an empty box or a random letter.
  • Rendering. Text anti-aliasing makes icons look slightly blurry, and they align like text, which often means fiddly vertical nudging.
  • Weight. You download the whole set, even if the page uses five icons.
  • One color. Each icon is a single glyph, so multi-color icons need stacking tricks.

If you maintain a project that uses an icon font, it still works. For new work, SVG solves every item on that list.

What about emoji? Emoji are fine for friendly, casual touches, but they look different on every operating system, can't be recolored, and screen readers read their full names aloud ("grinning face with big eyes"). Use them as content, not as interface icons.

Icon libraries from a CDN

Most projects do not draw icons by hand; they pull from a library. Two names appear everywhere, and both can be added with one <link> or <script> tag. They use different techniques, which is a good way to remember what each one does.

Font Awesome gives each icon a class name. You add the library's stylesheet (or a project "kit" script from your account), then write an element with a style class and an icon class:

HTML
<link rel="stylesheet" href="https://example-cdn.test/fontawesome/css/all.min.css">

<i class="fa-solid fa-house" aria-hidden="true"></i>
<i class="fa-regular fa-envelope" aria-hidden="true"></i>
<i class="fa-brands fa-github fa-2x" aria-hidden="true"></i>

The stylesheet sets the font family on the element and inserts the glyph with ::before, exactly like the icon-font pattern above. Size comes from the element's font-size (or helper classes such as fa-2x), and color from color. A free set exists, and some styles and icons need a paid plan. The library can also deliver SVG instead of a font, which avoids most icon-font drawbacks.

Google's Material Icons and Material Symbols use ligatures. The icon font knows that the letters of an icon's name should be replaced by the icon, so you write the name as text:

HTML
<link rel="stylesheet" href="https://example-cdn.test/material-symbols/outlined.css">

<span class="material-symbols-outlined" aria-hidden="true">home</span>
<span class="material-symbols-outlined" aria-hidden="true">favorite</span>

The word home becomes a house because the font contains a ligature for it. Material Symbols is a variable font, so you can adjust fill, weight, grade and optical size with font-variation-settings (for example 'FILL' 1). If the font fails to load, the word itself is shown, which is why the text is hidden from assistive technology with aria-hidden, and the meaning must come from a visible label or an aria-label on the button.

The example-cdn.test addresses above are placeholders. Use the current link from each project's own documentation, and pin a version number.

Question Font Awesome Material Symbols
How do you name an icon? Class: fa-house Text: home
How does it appear? ::before glyph Font ligature
Customizing Color, size, helper classes The same, plus variable-font axes
Delivery CSS and fonts, kits, or SVG Font (or SVG downloads)

Whichever you use, keep the accessibility rule from the next section: decorative icons get aria-hidden="true", and an icon that is the only content of a button needs a text alternative. Do not load a whole library for five icons; copy those five as inline SVG instead (see the sprite section above).

Accessible icons

Every icon is one of two kinds, and each has a simple rule.

Decorative icons sit next to text that already says the same thing, like the star beside "Favorites". Hide them from assistive technology so the label isn't announced twice:

HTML
<button>
  <svg aria-hidden="true" class="icon">...</svg>
  Favorites
</button>

Meaningful icons carry information that isn't written anywhere else. The classic case is an icon-only button. The button needs a text name, either through aria-label or through visually hidden text (see Accessible CSS):

HTML
<button aria-label="Close dialog">
  <svg aria-hidden="true" class="icon">...</svg>
</button>

<!-- or -->
<button>
  <svg aria-hidden="true" class="icon">...</svg>
  <span class="visually-hidden">Close dialog</span>
</button>

The name goes on the button, not the SVG, because the button is the thing people interact with. A standalone meaningful SVG (not inside a control) can use role="img" and aria-label instead.

A few more habits:

  • Give icon-only controls a large enough target. The icon can be small, but the button around it should be at least 24 by 24 pixels, ideally 44 by 44 for touch.
  • Check contrast. Icons that convey meaning need at least 3:1 contrast with their background.
  • Support forced colors. Icons that use currentColor follow the user's system colors in Windows High Contrast mode automatically. Icons with hard-coded colors may vanish.
  • Add a tooltip for unclear icons. Many icons aren't universally understood. A visible label is best; a tooltip is a reasonable second choice.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why set an icon's fill to currentColor?

    currentColor is the value of the color property, so the icon follows whatever text color applies, with no icon-specific rules.
  2. 2. What is the benefit of sizing icons with width and height of 1em?

    One em equals the current font size, so icons in big headings grow and icons in small print shrink automatically.
  3. 3. Your sprite works with <use href="#i-search"> but fails with <use href="https://cdn.example.net/icons.svg#i-search">. Why?

    Browsers only load external sprite files from the page's own origin. Host the sprite on your site.
  4. 4. Which is NOT a drawback of icon fonts?

    Icon fonts do follow the text color. Their problems are accessibility, fragile loading, rendering quality and file size.
  5. 5. How should you label an icon-only "Close" button?

    The button is the control, so it gets the accessible name. Hiding the SVG avoids announcing it separately.

Summary

  • SVG is the modern default for icons: sharp at every size, small, and styleable.
  • fill: currentColor (or stroke: currentColor) makes icons follow the text color; width and height of 1em make them follow the font size.
  • Align icons with labels using inline-flex, align-items: center and gap, or nudge inline icons with vertical-align.
  • Sprites define each icon once with <symbol> and reuse it with <use>; external sprite files must be same-origin.
  • mask-image with background-color: currentColor adds recolorable icons from CSS alone, ideal for pseudo-elements.
  • Icon fonts are legacy: they cause accessibility, loading and rendering problems.
  • Hide decorative icons with aria-hidden="true"; give icon-only controls an accessible name on the control itself.

Next: Dropdown Menus, where you build menus that open on hover, focus or click, and work with a keyboard.