How to Change the Colors of SLDS Icons Easily with this New Developer Feature

How to Change the Colors of SLDS Icons Easily with this New Developer Feature

REAL-TIME USE-CASE

Developers at Cloud Kicks need to change the colors of SLDS icons in their LWC components according to the company’s brand colors (like in the image above).

HELLO, STYLING HOOKS!

Styling hooks use CSS custom properties which make it easy to customise component styling and express your brand.
Let’s see them in action!

FOR UTILITY ICONS

Let’s get an icon in our LWC Component using the lightning-icon base component.

colourfulIcon.html

<lightning-icon 
    icon-name="utility:connected_apps" 
    alternative-text="Connected Apps" 
    title="Connected Apps" 
></lightning-icon>

Now, let’s add the Styling Hook to change the icon color (in line 2)

colourfulIcon.css

lightning-icon{
    --sds-c-icon-color-foreground-default: #FCB95B;
}

Note: The above CSS we are using the lightning-icon selector(line 1 in the above code snippet – colourfulIcon.css). This modifies the colours of all the icons in our component. If you would like to modify specific icons you can give the icons a class and use that as the selector instead (like in the example below)

FOR ICON TYPES – STANDARD, CUSTOM & ACTION

Let’s get another icon in our LWC Component using the lightning-icon base component and give it a CSS class which is used to select specific icons

anotherColourfulIcon.html

<template>
    <lightning-icon 
        icon-name="action:new_opportunity" 
        alternative-text="New Opportunity" 
        title="New Opportunity"
        class="customIcon"
    ></lightning-icon>
</template>

Unlike the utility icon which is single color, the Standard, Custom & Action icons we use different Styling Hooks as these icon types have 2 colors – a background and a foreground color

Now, using the custom CSS class we select our icon(line 1) and add the relevant Styling Hooks to change both background and foreground colors (in line 2 & 3) of the icon

anotherColourfulIcon.css

.customIcon{
    --sds-c-icon-color-background: #F96167;
    --sds-c-icon-color-foreground: #FCE77D;
}

RESOURCES

Happy Colouring! Thank you for checking this out, take care, stay safe & I’ll see you in the next one!