Code Reference

Icons

CSS · Reference cheat sheet

Icons

CSS · Reference cheat sheet


📋 Overview

Icons in CSS-driven UIs are usually inline SVG, icon fonts, or mask/background images. Inline SVG is preferred for accessibility, theming via currentColor, and crisp scaling. Style icons to align with text, inherit color, and keep decorative icons hidden from assistive tech with aria-hidden="true".

Treat icon size as a design token (1em or fixed rem) so icons scale with surrounding type when appropriate.

🔧 Core concepts

Delivery techniques

TechniqueProsCons
Inline SVGColorable, accessible, CSS-targetableMarkup weight if not sprited
<img src="*.svg">Simple cachingHarder to recolor
CSS mask-imageRecolor with background-colorNeeds careful sizing
Icon fontEasy swapLigature/a11y pitfalls, FOIT
Sprite / symbol <use>Deduplicates pathsCross-origin/use quirks

Alignment & sizing

Property / tipWhy
inline-size / block-sizeExplicit box
flex-shrink: 0Prevent crush in flex rows
vertical-align: -0.125emOptical align with text
display: block on SVG in buttonsRemove baseline gap

Theming with currentColor

.icon {
  inline-size: 1.25rem;
  block-size: 1.25rem;
  fill: currentColor; /* or stroke for outline icons */
}

Parent color then drives the icon.

💡 Examples

Button with inline SVG

<button type="button" class="btn">
  <svg class="icon" aria-hidden="true" focusable="false" viewBox="0 0 24 24">
    <path d="…" />
  </svg>
  Download
</button>
.btn {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
}

.icon {
  inline-size: 1.125rem;
  block-size: 1.125rem;
  fill: currentColor;
  flex-shrink: 0;
}

Mask-based icon

.icon-mask {
  display: inline-block;
  inline-size: 1.25rem;
  block-size: 1.25rem;
  background-color: currentColor;
  mask: url("/icons/check.svg") center / contain no-repeat;
  -webkit-mask: url("/icons/check.svg") center / contain no-repeat;
}

Optical alignment in text

.with-icon {
  display: inline-flex;
  align-items: center;
  gap: 0.35em;
}

.with-icon .icon {
  inline-size: 1em;
  block-size: 1em;
}

Standalone icon button (accessible name)

<button type="button" class="icon-btn" aria-label="Close">
  <svg class="icon" aria-hidden="true" focusable="false">…</svg>
</button>
.icon-btn {
  display: inline-grid;
  place-items: center;
  inline-size: 2.5rem;
  block-size: 2.5rem;
  padding: 0;
}

⚠️ Pitfalls

  • Using icon fonts with ligature text that screen readers announce as random letters—prefer SVG + accessible names.
  • Leaving SVG focusable in some browsers without focusable="false" inside buttons.
  • Scaling icons with only font-size on icon fonts while stroke widths look uneven—prefer SVG.
  • Crushing icons in flex layouts without flex-shrink: 0.
  • Decorative icons without aria-hidden that add noise to the accessibility tree.

On this page