You can share the common CSS styles across multiple LWCs by creating CSS utility components. There are some benefits of having shared CSS styles rather than simply copying-pasting them into multiple components.
- It helps reduce redundancy.
- One single source in case you need to update the styles across all components.
- Easy to use and extend.
- Clean and nice stylesheets.
Sharing your styles across multiple Lwc's
For example, I have created some sample styling that I want to share across multiple components. Here are the styles that I want to share.
sharedStyles.css
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
.my-shared-color-primary { background-color: #006778; color: white; } .my-shared-color-secondary { background-color: #0093ab; color: white; } .my-shared-color-accent { color: black; background-color: #ffd124; } .my-shared-header { font-size: 20px; font-weight: bold; } .my-shared-header_small { font-size: 15px; font-weight: bold; } |
This is how its output looks on the page.
Steps to share CSS across multiple Lwc's
-
Create a new Lightning web component with the proper name, I will name it
sharedStyles
for this example. - Open the newly created component in the files explorer from your IDE, I am using VS Code.
-
Delete the
.html
and.js
files from the newly created component. -
Create a new file
<componentName>.css
, itssharedStyles.css
in my case. - Put your styles into the new CSS files.
- Deploy your component to org.
-
Now go to the component where you want to utilize these styles, for
example:
sharedStyleExample1
-
Create a CSS file if not already exists in your target component.
sharedStyleExample1.css
-
Import the utility component into the target component.
1 2 3 4 5 6 7 8 9 10 11 12
@import "c/sharedStyles"; /* You can override the common shared styles here. Example: this is my class from common shared css my-shared-color-secondary .my-shared-color-secondary { background-color: rgb(228, 155, 37); color: black; } */ /* add other styles specific to your component */
- Deploy your component.
- And you have successfully applied shared styles to your component.
Follow the steps from 7 to 11 for all of your other components where you want to apply the common shared styles. You can create multiple utility components and also import multiple of them into a single component.
Additionally, you can override the styles from the shared component if needed.
1 2 3 4 5 6 |
@import "c/sharedStyles"; .my-shared-color-secondary { background-color: rgb(228, 155, 37); color: black; } |
Thanks for visiting, please let me know if this was helpful!
No comments :
Post a Comment
Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com