Lightning : Icon color is not changing using the fill CSS

2.0K    Asked by CarolynBuckland in Salesforce , Asked on Apr 22, 2021

 According to the documentation (https://www.lightningdesignsystem.com/components/icons/ ) we can change the icon color by using the CSS. I am not able to do it. It always overrides with the Salesforce style. My Style class is as below:  THIS .icn{ fill: white; } Other CSS properties like background color are applying but fill is always getting overridden by salesforce default color (grey). Anyone have any idea on how to fix this?


Answered by Dipesh Bhardwaj

Actually the issue is which element you are applying the "fill" property to. Meaning when you declare something like . It gets rendered as follows HTML Render If you notice the "icn" is applied to the outer span container rather than svg itself. Hence you will have to do Something as follows to apply your custom styles. ( applying the css to the svg element using heirarchies )Svg Icon Colored Updated for LWC components. (18/03/2021)The above mentioned approach would not work for lightning web components such as lightning-icon as the web components use a shadow root property "closed" - which prevents us from modifying styles or accessing attributes from different namespaces. Luckily Salesforce has introduced Styling Hooks for us to customize the icon styles. Add a class attribute to the lightning-icon component. And add the following properties to your css class to customize icons.

.comments-icn{
   --sds-c-icon-color-foreground-default: orange; //utility icons
   --sds-c-icon-color-foreground: orange; //action icons or custom icons
   --sds-c-icon-color-background: white; //action icons or custom icons
}

It Could be a release related thing (some update to the DOM structure) or if there is a shadow root intervention for the out of box components - then this approach might cause discrepancies as this relies on the DOM heirarchy & CSS Specificity. Nevertheless please feel free to update your approach with an example for the future audience. This way you can change the lightning icon



Your Answer

Answer (1)

If the color of a Lightning icon is not changing using the fill CSS property, try these steps:


1 .Use slds-icon-text-default Class: 

Add the slds-icon-text-default class to the icon to use the standard SLDS color classes.

2. Override fill Property:

Ensure that your CSS is correctly overriding the default styles:

.custom-icon {
    fill: red !important;
}

Inline SVG Styles:

If the icon is an inline SVG, directly set the fill attribute within the SVG element:   

Use SLDS Utility Classes:

Use Salesforce Lightning Design System (SLDS) utility classes to change the color:

By following these steps, you should be able to change the icon color successfully.

4 Months

Interviews

Parent Categories