Share CSS Style Rules

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

You can import one or more CSS modules. The imported style rules apply to the template just like non-imported style rules. Lightning Web Components (LWC) supports the CSS cascade algorithm.

1/* myComponent.css */
2
3/* Syntax */
4@import "namespace/moduleName";
5
6/* Example */
7@import "c/cssLibrary";
8
9/* Note: Lightning web components can access modules only from the c and lightning namespaces
10under Lightning Locker. If Lightning Web Security is enabled, Lightning web components 
11can access modules from other namespaces. */

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

  1. Create a Lightning web component that contains a CSS file and a configuration file. The folder and filenames must be identical. This component is your CSS module.

    1cssLibrary
    2   ├──cssLibrary.css
    3   └──cssLibrary.js-meta.xml
  2. Define the style rules in the CSS file.

    1/* cssLibrary.css */
    2h1 {
    3  font-size: xx-large;
    4}
  3. The configuration file requires only these tags.

    1<!-- cssLibrary.js-meta.xml -->
    2<?xml version="1.0" encoding="UTF-8" ?>
    3<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    4    <apiVersion>49.0</apiVersion>
    5    <isExposed>false</isExposed>
    6</LightningComponentBundle>
  4. In the CSS file of a Lightning web component, import the CSS module.

    1myComponent
    2   ├──myComponent.html
    3   ├──myComponent.js
    4   ├──myComponent.js-meta.xml
    5   └──myComponent.css
    1/* myComponent.css */
    2@import "c/cssLibrary";
    3
    4/* Define other style rules for myComponent here */
  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.

    1<!-- myComponent.html -->
    2
    3<template>
    4  <h1>Words to the Wise</h1>
    5  <p>An apple a day keeps the doctor away.</p>
    6</template>

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

Tip

See Also