Share CSS Styles Among Lightning Web Components

Create a consistent look and feel for Lightning web components by using a common CSS module. Define styles in the CSS module, and import the module into the components that share those styles.

Where: This change applies to Lightning web components in Lightning Experience and all versions of the Salesforce app.

How:
  1. 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
  2. In the CSS file, define the style rules to share.
    /* cssLibrary.css */
    h1 {
        font-size: xx-large;
    }
  3. 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>
  4. In the CSS file of a Lightning web component, 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 */

    You can import one or more CSS modules.

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

    Important

    For more information about @import, see MDN web docs: @import. MDN lists two syntax styles: @import url and @import url list-of-media-queries. LWC doesn’t honor the list-of-media-queries.

  5. 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>
Tip

Tip

You can play with the code in a playground at lwc.dev/guide/css.