Working with vector icons on the frontend has long been an awkward trade-off: inline SVGs bloat the DOM and forfeit browser caching, while loading them via <img> strips away your ability to recolor them dynamically with currentColor. I kept hunting for a happy medium until I tried pairing mask-image with CSS custom properties.
The idea is simple: you create a base element with a mask bound to a CSS variable, and control the fill color using a plain background-color:
/* Base styles for the masked icon */
.icon {
display: inline-block;
width: 24px;
height: 24px;
background-color: currentColor;
-webkit-mask: var(--icon-url) no-repeat center / contain;
mask: var(--icon-url) no-repeat center / contain;
}
.action-btn:hover .icon {
--icon-url: url("/icons/star-active.svg");
}
In your HTML, the icon stays clean and needs zero JavaScript to swap states:
<!-- Action button with a dynamic mask -->
<button class="action-btn">
<span class="icon" style="--icon-url: url('/icons/star-idle.svg');"></span>
<span>Bookmark</span>
</button>
Your SVG files remain external assets that cache cleanly, the color automatically inherits from the parent text, and swapping graphics takes just one variable override in your stylesheet.
