CSS Icons
CSS Icons: Styling Crisp Vector Icons and Button Alignment
Modern web interfaces use icons for navigation bars, alert banners, search inputs, and status badges. While older projects relied on icon fonts (i tags with custom font files), modern CSS pairs inline SVG icons with Flexbox alignment and currentColor for sharper edges, smaller payloads, and reliable accessibility.
Styling Inline SVGs with CSS
Inline SVGs inherit the parent button or link's color automatically when you set stroke="currentColor" or fill="currentColor". Sizing icons with width: 1.125em; height: 1.125em; scales each icon proportionally whenever the button text size changes.
.icon-btn {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 10px 16px;
background-color: #1e293b;
color: #f8fafc;
border-radius: 6px;
border: none;
cursor: pointer;
}
.icon-btn svg {
width: 18px;
height: 18px;
flex-shrink: 0;
stroke: currentColor;
}
.icon-btn:hover {
background-color: #2563eb;
}
Accessibility Rules for Icons
Every icon falls into one of two categories:
- Decorative Icons: Paired beside visible text (such as a trash icon next to "Delete"). Add
aria-hidden="true"on thesvgoriso screen readers do not announce gibberish. - Standalone Icon Buttons: Buttons without visible text (like a close
Xor menu hamburger). Addaria-label="Close modal"on thebuttonandaria-hidden="true"on the icon inside.
Common Mistakes to Avoid
- Aligning icons beside text with
vertical-alignhacks: Settingdisplay: inline-flex; align-items: center; gap: 8px;on the parent button centers icons vertically every time. - Loading a 300 KB icon font CSS file for five icons: Extract only the inline SVG icons you actually use to keep pages fast.
- Forgetting
flex-shrink: 0on icons inside narrow buttons: Without it, long button text squishes the SVG horizontally.
Frequently Asked Questions
Why are inline SVGs preferred over icon fonts today?
Inline SVGs render crisply without font-loading flashes (FOIT), support multi-color paths, and avoid screen reader glitches when custom fonts fail to download.
How do I recolor an external SVG background icon in CSS?
Use CSS mask-image: url("icon.svg"); background-color: currentColor; so the SVG acts as a stencil filled by your active CSS text color.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.