The best way to use icons in Web UIs
I’ve always had a soft spot for icons 1 . Not only do they add polish to a UI, they can also tangibly improve usability. Familiar icons help users find what they need quickly, since we recognize pictures much faster than we read words. And as a web architect at heart, the current dominant ways we have to include icons on the Web make me sad. While there are many, many different ways to include icons in a Web UI, each with different performance characteristics , by far the most common ones involve adding inline SVG to the HTML. For example, a trash icon might be included like this: Some people use a separate SVG file for sanity and include icons via , but the markup is still fairly clunky (not to mention slow, sans bundlers). All this clunkiness forces people to resort to hiding the icon under layers of abstraction, such as dedicated custom elements like or React components like , but the ugliness still ships under all these layers, and the browser still has to deal with it. Icon fonts did put icons in CSS ( is still how Font Awesome’s pseudo-element mode works), and a lot of their appeal was exactly that. But they came with a long list of issues : large downloads (even with subsetting), fallback glyphs when the font fails to load, screen readers announcing private-use codepoints, user font overrides (e.g. for dyslexia) wiping them out, and text hinting that was never designed for pictures. We threw out the baby with the bathwater: the problem was the font, not the CSS. Many of the attempts to move this to CSS still involve markup. The mask trick that most of them rely on is not new either: Chen Hui Jing covered it in 2021, and Iconify generates mask-based CSS for its entire catalog. But in all of these, which icon to use (and whether to use one at all) is still decided in the markup, via one class per icon; CSS only handles color. The closest I’ve seen is David Bushell’s 2024 post on including icons purely via CSS via generated content + masks, where the icon is picked in CSS, but every selector that wants to support icons needs its own chunk of CSS, and there is no way to override the icon on a case by case basis. I still think it’s superior to inline SVG in HTML, and it baffles me why it isn’t more popular. Per the principles outlined in my user effort article , a good icon system should: How does that translate to an icon system? Per consumers > producers , making icon usage ergonomic is more important than making icon definition ergonomic, but ideally adding a new icon to the icon system should not require much more than: And of course, it still needs to be reasonably performant — the existing success criteria don’t disappear! The dominant ways to include icons today fail to meet at least one of these criteria. Can we do better? CSS is the only web platform language that facilitates reactive aggregation : you declare what applies to what conditions (type of element, interaction state, media query, etc.) and the browser automatically applies the right styles when those conditions are met and cleanly removes them when they are no longer met, without affecting any other conditions that simultaneously apply to the element, and without forcing developers to manage any of these side effects manually. I personally think we are underutilizing this wonderful language by artificially restricting it to styling, but that’s a topic for another article. If we can nail icons via CSS, this gives us tremendous expressive power, with practically no loss of flexibility. Imagine being able to tweak icons based on… Additionally, if icons can be injected or tweaked via CSS, this means we can specify them on pseudo-elements, such as , , or , something no markup solution accommodates. Or even, imagine applying entirely different icon sets to the entire page (or a portion) without having to touch any markup! E.g. a section with a hand-drawn aesthetic could get a hand-drawn icon set, without affecting the rest of the UI. The possibilities are endless. Once you allow yourself to consider that this is possible, you will start seeing use cases everywhere. Including icons as direct s (especially with no wrapping abstraction to manage a shared registry) means there is no way to enforce consistency — anything goes. One page might use a Font Awesome trash icon, another might use a Lucide trash icon. I think the icons themselves should be a type of design token, managed by the design system, that UI components simply use, just like colors and gradients. Managing icons via CSS also allows us to define them alongside other design tokens (e.g. as CSS variables on ), rather than in a separate place. Suppose icons were CSS variables, and we could add an icon to an element simply by setting an custom property, e.g. by doing something like This means we could also make simple things easy via: while maintaining the ability to override the icon on a case by case basis by simply overridding the property. We can even adapt to state reactively: or user interaction, e.g. to communicate both where a link goes (GitHub) and what it is (an external link): And for completely ad hoc standalone icons where adding CSS would be more work than doing it inline in HTML, we can have an class: This makes it strictly more powerful than the markup approaches , with the only exception being that completely inline SVG allows potentially changing the SVG itself in arbitrary ways (e.g. morphing it into another icon or changing it dynamically as the result of user input). For those cases, we’d still need inline SVGs. But how many of your icons fall in that category? The core idea can be summarized as: Icons are inserted via pseudo-elements, which use the icon to mask a square with equal to the icon color. The referencing syntax I’ve settled on is: You could be more elaborate and also define properties like , etc, if you deem them useful! The beauty of this approach is its immense flexibility. Available icons are defined on as CSS variables, e.g.: One-off icons can still be used by setting e.g. instead of , but if most UI references registered icons, they will stand out like a sore thumb and will be easy to spot in a review. Then, to display these as icons, the crux is: For simplicity, I will only discuss / in the rest of this section, but everything applies identically to / and any additional ones. You may be wondering why I’m specifying the size twice instead of . Flex items stretch by default, and a stretched size is definite, so is ignored. Since icons so often live in buttons, and buttons are so often , an explicit is far more robust. Grid happens to be fine ( behaves as for items with an aspect ratio), but flex has no such exception. Unfortunately, you need to repeat the pseudo-element contents for every type of pseudo-element you want to be able to support icons on. Mixins will eventually fix that. As described above, this would apply to all elements, which is far from ideal! We can use a style query ( finally Baseline! 🎉 ) to restrict this to only elements with the property set: We would also need to register as non-inheriting via , otherwise any container with an icon would sprout an icon for every single descendant (including inline formatting like , etc!), which we definitely don’t want. And then just explicitly inherit them in the pseudo-element: Style queries are Baseline 2026 , which sounds quite cutting edge. However, if you look at market share, it is supported in ~93% of users’ browsers worldwide per Can I Use data. While this data under-represents old Chrome Android (it lumps all Chrome Android under its latest version), Chrome shipped style queries in 2023 (in version 111) and Chrome Mobile users do seem to upgrade pretty quickly , so the real number won’t be meaningfully lower. How is this possible? If you sort by date, you will see that all major browsers except Firefox had shipped style queries by 2024. Firefox was the last one to ship them, in May 2026. Now, let’s see the Usage relative chart: Firefox as a whole accounts for 2.28% of worldwide market share. Now, I’m not saying ignore Firefox because of its low market share! That would be a d*ck move, comparable to making UIs inaccessible because screen reader users are a minority. Some things matter more than their raw numbers might indicate , and not excluding Firefox is essential for the Web to remain open, interoperable, and not controlled solely by large companies. That said, for features that have shipped in every major browser, I think it’s defensible to take market share into account. Baseline tiers are a great …baseline, but no compact metric could possibly convey this kind of granularity. Especially for something like this, where things generally still work fine without icons, it’s a plausible strategy to treat icons as a progressive enhancement and just accept not having them in the 7% of browsers that don’t support them. For the cases where icons are crucial, (e.g. icon-only controls) we can use a class (e.g. , , , etc), so that older browsers with no style query support still get them. Then, how much you want to lean in to progressive enhancement depends on how widely you rely on the class vs the style query. You could even add other known selectors to it e.g. inline styles or known selectors with icons: Do note that unrestricted attribute selectors like that can be slow, so use them judiciously. One issue with the class approach is that it hardcodes icon presence , even if you can still tweak the icon itself via CSS custom properties. One way to deal with this is to specify a value that becomes IACVT if the custom property has no value, which would make the entire pseudo-element disappear: This will resolve to a transparent image if is defined, and to → if it is not, which will effectively remove the pseudo-element. And yes, is Baseline Widely Available . It doesn’t remove any of the other properties, so it still cannot compose with other styles, so don’t apply it so broadly it can clash with other elements that may have styles. The styles above are a start, but we can do better: Putting it all together so far, we get something like this If you’re viewing the demo in Chrome or Firefox, it should work as expected. If you’re viewing the demo in Safari, you’ll already know that it’s severely broken. My research on this resulted in filing not one, but two Safari bug reports. The good news is that all have workarounds. The bad news is that these workarounds force us into suboptimal code, and unless we’re willing to ship a different version to Safari, everyone suffers. WebKit bug #301609 was the one that really threw a spanner in the works the most for this technique: The tl;dr is if you use what I wrote above, the icons will not show up in Safari until the user interacts with them in some way (e.g. hover, focus, etc.). Thankfully, I found a CSS workaround: However, since this applies an animation to all and pseudo-elements, ideally we’d want to restrict it a bit, and make it easier to override by wrapping it in a layer. Turns out this seems to magically also fix WebKit bug #320220 , which is also relevant here. At this point our demo works almost perfectly! Can you spot the bug that remains? There are two buttons that change their icon on hover: Default icon and Github to link . The former works, the latter doesn’t. WAT?! So, there is a difference between them: sets on hover, whereas Github to link sets directly, via . And is registered as non-inheriting, which is quite relevant here. Turns out that used to not work at all in Safari until 2023 , and there are still some cases where it reproduces today. The investigation resulted in WebKit bug #325900 being filed. There are a few solutions here of which the only workable one seems to be to register the property as inherited after all, and add a style query that resets it on descendants: It’s a bit more fragile and likely slower, so ideally we’d only ship it to Safari. can only detect features, not bugs, so once more we have to resort to sniffing WebKit. Conveniently, is allowed inside conditional rules, and when a property is registered multiple times, the last registration wins: The layer means any unlayered declaration wins over the reset, even zero-specificity ones like . Putting it all together, here is the final demo, with both workarounds applied: When using icons from SVG files it’s important to remember that any relative URL will resolve relative to the CSS file that uses the icon, not the one it’s defined in . In practice, this forces you to use root-relative URLs (e.g. ), otherwise you’ll have random breakage in any nontrivial project structure. An alternative is to register the icon properties as via and specify their values via : This is also better for other reasons: The obvious downside is DX: there is a lot more boilerplate to define an icon this way. The earlier syntax can be managed by hand, even for many icons. This starts requiring a build step after a dozen or so. Additionally, registered properties are currently global and don’t work in shadow roots , so that may not fit every use case. Another option might be to go through all properties in and register them via JS: An even cleaner option, if you know which stylesheet includes the icon tokens (and it’s same-origin) is to use the CSS OM to actually edit it, so that the declarations are removed once you register the properties: Since the icon is a mask, this technique only works for monochrome icons (varied opacity is fine) — but most icons are monochrome these days anyway. If you really need more, Allegro’s engineers stack masks on the element and both its pseudo-elements, which gets you up to three colors from a single element. But what about full color icons, e.g. emojis? Or textual icons, e.g. …emojis? In theory, the technique can work fine with them, these are actually easier! For full color icons you just set them as background images, no masking required. And for textual icons, you can just set them directly on the property. The only challenge here is branching between these three. But this may be the subject of a future post, as this is already getting quite long. Since the entire pseudo-element is masked, you cannot apply a separate background or border to it. For that, you’d need an actual element (e.g. ), and you can apply the borders, backgrounds, etc to that. Completely arbitrary animation would obviously still require inline elements. But what about predefined animations? A checkmark or X being drawn, a hamburger animating to a close button, etc.? I thought I had figured out a way. And I did get so close! Close enough that the whole saga deserves its own post, so stay tuned 😉 The system above gets us pretty good DX (especially without the Safari bugs!), but some things are still not ideal. First, the masking approach does introduce some limitations it would be nice to be able to get rid of. Then, signal-to-noise ratio could be even better: And while consumers > producers, it would be really nice if adding support for new pseudo-element types did not require such a song-and-dance. A number of upcoming CSS features get us closer to this North Star . If you haven’t heard of the new CSS Linked Parameters spec, it’s the best thing that has happened to CSS icons in a long time. It allows us to pass arbitrary data to any resource that supports it (and yes, SVG is one of them), which means we can customize icons in ways that were previously impossible, such as changing the stroke width, color, or even entirely arbitrary customizations, since SVG also supports style queries. And as of a couple weeks ago, it also supports passing and without any double opt-in from the icon, which means we can use any existing icon library without it having to be updated to utilize them! There are some limitations still, but it is being actively designed, Firefox has shipped an earlier version of the spec , and is one of the top Interop 2027 proposals , so I’m quite hopeful it can make it much easier to use icons in CSS. Keep a close eye on that one! Currently, due to a technicality in how the property is handled, we have to rely on background images to include icons, because otherwise and don’t work. Even Link Parameters by itself won’t change that, it will just allow us to get rid of the masking hack. Thankfully, we (CSS WG) recently resolved on a change that will fix this! (pending compat analysis) is the CSS feature you didn’t know you were desperate for, and deserves an article of its own for its myriad of use cases in design systems. Until I write that, Bramus has a great write-up . But more relevant to icons, once is widely supported, we can construct variable names dynamically, meaning we can use plain identifiers instead of CSS variables, which will make the syntax even cleaner, meaning we’d be able to translate into at the cost of a little complexity on the producer side: Yes, it’s ugly, but it’s also an implementation detail that’s not exposed to icon consumers, so I think the tradeoff is worth it. Combined with expanded , which is getting there with only Safari remaining (Safari TP already supports it), this also unlocks ad hoc icons via a plain attribute: We recently resolved to support registering multiple properties with the same descriptors at once via , this won’t help much here, since we need different initial values. You could of course register multiple properties with the syntax and then also set their actual icons on but now you need to add each icon in two places, so I’d consider it worse than the current expanded syntax. However, another direction we are exploring in the CSS WG is a shorthand form of that would allow more compact registration. For the icon above it would look like this: Currently, we have to repeat a lot of styles between the different pseudo-elements. If we want to also have a fallback class that doesn’t depend on style queries, we need to repeat them four times! With we can just do: And then we can use them all over the place: I published a package that puts together everything from this post, polish and warts included. It contains no icons, just the icon system. You’d just include it and then you can use and in your styles. It also includes the , , and classes. It does not wrap its contents in a layer to give you maximum choice, but I’d recommend importing it in a layer anyway. @nudeui/icons There’s a small chance I may have been the first to use a web font for UI icons , in 2010. I even worked as Product Lead at Font Awesome for a bit. ↩︎ I’m using “components” here in the general sense of a reusable UI element, not in the sense of a framework component or a custom element. E.g. a styled or an would qualify. ↩︎ keep syntax close to the minimum necessary to declare intent , and make simple things easy, complex things possible, and the transition from one to the other smooth (no usability cliffs) High signal-to-noise ratio: The intent to add or override an icon is basically “icon” plus the icon name, and possibly its location (start, end, marker, etc). Anything beyond that is boilerplate. Some boilerplate is unavoidable, but most -based solutions involve unacceptable amounts of boilerplate (which is why we end up abstracting that away). Simple things should be easy: We should be able to define default icons for certain cases without having to explicitly include them at every callsite. E.g. a should automatically get a trash icon, without needing to declare it in the markup in any way, shape, or form, unless we want to override it. The default icon color should follow the local text color (or designated icon color, if different) without any additional song and dance. Complex things should be possible: We should be able to easily override the default icon for a component, either permanently or as a result of various conditions (state changes, user interaction, etc.). Styling the icon should be as easy as applying a CSS property. The minimum is color, but the more extensive styling is possible, the better. No usability cliffs: Overridding an icon, temporarily or permanently, should still not require much more than the bits of information necessary to declare intent. declaring the name of the icon, and providing the SVG path data or a URL to an SVG file Any selector, including interaction pseudo-classes ( , , etc.), e.g. to communicate additional information about the action or adapt to a different background color Media queries ( , dark mode, high contrast, etc), e.g. use different icons in dark mode, add or remove them in print, etc. Container queries Writing mode, e.g. to use a different icon for RTL text Icons are first-class design tokens stored in properties that hold values (embedded or remote) Icons are inserted via pseudo-elements. The icon is applied as a mask to a square with equal to the icon color. The system uses general CSS custom properties like , , and for flexibility and reusability. Style queries + for conditional icon insertion based on these custom properties. Low-level properties: to prepend an icon to element contents (via ) to append an icon to element contents (via ) Optionally, additional properties can redirect to other pseudo-elements, e.g. for higher level abstraction that just means “add an icon to this component”: components 2 can redirect it to any of the lower-level properties on the element itself or a descendant depending on what makes sense for that component. E.g. may set on a but on An empty pseudo-element e.g. or is used to display the icon The pseudo-element is painted as a square with A CSS masks the square in the shape of the icon ( But, but, but …browser support?!? Fear not! Masks are actually Baseline Widely Available nowadays) A CSS property ( or ) is used to specify the icon to display, instead of an ad hoc one like . This means we can set any element’s icon from any place that accepts declaration, including via inline styles Customizable color and size : Rather than hardcoding and , read them from custom properties with those as fallbacks: and (same for ). Since they inherit, you can style every icon in a subtree by setting them on an ancestor, without ever touching the pseudo-element. The prefix keeps them from colliding with the icons themselves, which are also . Preserve in forced colors mode : to keep the mask fill in forced-colors mode. will still follow the forced text color. Don’t get in the way of pointer interactions : so that it doesn’t trap clicks it shouldn’t. Don’t shrink in flex containers : . An empty pseudo-element has a zero minimum size, so in a flex button it is the first thing to shrink when the label is long, and it can shrink all the way to zero. An icon’s size is a design decision, not something layout pressure should negotiate. Vertical centering : I add to center the icons and nudge them a tiny bit upwards (our eyes weigh the space above the icon more than the space below it, so if something is perfectly centered mathematically, it will look a bit low). With a customizable size, that becomes , so that the icon’s center stays put as it grows. Spacing from text : to add a bit of space between the icon and the content ( for ). Make sure to remove it for standalone icons. Accessibility : The pseudo-element has no text, so assistive technology ignores it entirely, which is exactly what we want for an icon next to a label. Icon-only controls still need a name, and we can let the icon provide one via alternative text for generated content : , so that is announced as “Delete”. on the control itself still works, of course. There won’t be hundreds of variables in dev tools for You can even override it temporarily with another icon for a specific context, and reset it wherever via What if could work, instead of ? What if could work, instead of ? (ignoring HTML restrictions around attribute names for a bit) There’s a small chance I may have been the first to use a web font for UI icons , in 2010. I even worked as Product Lead at Font Awesome for a bit. ↩︎ I’m using “components” here in the general sense of a reusable UI element, not in the sense of a framework component or a custom element. E.g. a styled or an would qualify. ↩︎