Saturday, 8 August 2020

Share CSS Styles Among Lightning Web Components

 Hi,

From Summer 20 release onwards we can share CSS between Lightning Web Components by using a common CSS module.

It helps to maintain consistent look and feel for Lightning Web Components.

For that, we can define styles in the CSS module, and import the module into the components that share those styles.

Let's create a component that contains a CSS file and a configuration file.

The folder and filenames must be identical. This component is your CSS module.

cssLibrary
   ├──cssLibrary.css
   └──cssLibrary.js-meta.xml

In the CSS file, define the style rules to share.

/* cssLibrary.css */
h1 {
    font-size: xx-large;
}

The configuration file needs only these tags

<!-- cssLibrary.js-meta.xml --> 
<?xml version="1.0" encoding="UTF-8" ?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>49.0</apiVersion>
    <isExposed>false</isExposed>
</LightningComponentBundle>

You can import one or more CSS modules.

Syntax:

/* Syntax */
@import 'namespace/moduleName';

Now in the CSS file of other Lightning web components, import the module.

myComponent
   ├──myComponent.html
   ├──myComponent.js
   ├──myComponent.js-meta.xml
   └──myComponent.css
/* myComponent.css */
@import 'c/cssLibrary';

/* Define other style rules for myComponent here */

Imported style rules are applied to the template just like non-imported style rules. All style rules cascade. In the myComponent.html template, the text in the <h1> tag uses the xx-large style defined in cssLibrary.css.

<!-- myComponent.html -->

<template>
  <h1>Words to the Wise</h1>
  <p>An apple a day keeps the doctor away</p>
</template>


Reference:

https://lwc.dev/guide/css

https://developer.mozilla.org/en-US/docs/Web/CSS/@import


No comments:

Post a Comment

What’s the difference between Einstein Article Recommendations and Suggested Articles?

How Does Einstein Article Recommendations Work? Einstein Article Recommendations helps support agents resolve customer cases efficiently by ...