How to Override CSS of Inner Elements of Lightning Web Component?
- July 24, 2020
- 4 minutes
What is Lightning Web Component?
Generally we face difficulty in overriding inner elements of lightning web components. So here let’s see how we could do that.
Let’s take an example of lightning-input. It represents interactive controls that accept user input depending on the type attribute.
Date Input: Date input fields provide a date picker for entering a date.
Below example shows lightning-input type “date”
We are required to reduce the size of this calendar/datepicker which you can see in the above image.
- Lightningdatepicker.html (Lightning Web Component Template)
- It contains lightning-input of type “date”.
- Lightningdatepicker.css (Lightning Web Component CSS File)
- It contains css for lightning datepicker/calendar to reduce its size
The Output :
As we can see the above output is the same as original output i.e Fig. 1(a) . Even after applying css to slds-datepicker(lightning datepicker). This is due to datepicker not being accessible/visible to our component’s css because of the strict CSS isolation enforced by LWC. As in lightningelement.html we are not able to see any element such as datepicker because it is embedded inside <lightning-input></lightning-input> that acts as a wrapper for datepicker.
So to resolve this issue we need to put CSS that we wanted applied to the inner shadow DOM of Salesforce Base Components in a static resource. Then we used the loadStyle method of lightning/platformResourceLoader module to load that css.
- js (Lightning Web Component Js File)
- It contains the loadStyle method of lightning/platformResourceLoader module to load css. In this customMinifiedDp is a static resource which contains css file “customMinifiedDP.css”.
- css (Static Resource Css File)
The above CSS loaded through the loadStyle does allow overriding the inner elements while the CSS coming from the .CSS of the lightning bundle doesn’t allow this.
Output After Uploading Static Resource:
It shows the reduced size of the datepicker/calendar by overriding the inner elements of the lightning web component.
If you are thinking about building your app on the AppExchange, Contact us. At GetOnCRM Solutions, Our team of highly experienced Salesforce Lightning Experts can help you to customize and build beautiful apps and future for your platform on your unique business needs.