I came up with a new way to use custom SVG icons with ion-icons that maintains the flexibility to apply different colors with CSS color. With CSS masks!
First, I make sure I define all my icons with a special prefix in HTML like so
<ion-icon name="appname-customicon"></ion-icon>
Then I add this to my app.scss
// Custom icons
// Overriding the ion-icon behavior
// All custom icons will start with "appname-" prefix
ion-icon {
&[class*="appname-"] {
// Instead of using the font-based icons
// We're applying SVG masks
mask-size: contain;
mask-position: 50% 50%;
mask-repeat: no-repeat;
background: currentColor;
width: 1em;
height: 1em;
}
// custom icons
&[class*="appname-customicon1"] {
mask-image: url(../assets/img/customicon1.svg);
}
&[class*="appname-customicon2"] {
mask-image: url(../assets/img/customicon2.svg);
}
}
Basically what I’m doing is for all ion-icon elements with a class that contains “appname-”, define the background color to be what the foreground color to be. Then I’m setting a CSS mask to essentially mask the background with my custom icon SVG.
Because there won’t be any content, I need to manually set the size to be a square the size of an font em.
I can then define as many custom icons as I wish by simply adding a new rule. I just have to be careful not to have any rules that are subsets of another since I have to use the CSS attribute value ANY selector.
You can also define a different SVG for the “outline” version by adding a new rule.