LWC 共通 CSS 方法説明
-
スタイルシートを使用して共通の CSS を定義し、それを複数のコンポーネントでインポートします。
-
CSS をグローバルに定義し、それをすべてのコンポーネントで使用します。
-
コンポーネントのスコープ内に CSS を定義し、それをそのコンポーネント内でのみ使用します。
-
CSS Modules を使用して、インポート済みのスタイルシートをスコープ化します。
ソース構成図
lwc
├─commonStyle
└─commonStyleChild
commonStyle

commonStyle.css
.commonCss {
font-size: 30px;
color: #fff;
background-color: rgba(128, 129, 56, 0.5);
border-radius: 2px;
min-width: 100px;
/** 真ん中 */
display: flex;
justify-content: center;
align-items: center;
}
commonStyle.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>52.0</apiVersion>
<isExposed>false</isExposed>
</LightningComponentBundle>
commonStyleChild

commonStyleChild.css
@import "c/commonStyle"; /**ここ共通CSSをインポート*/
commonStyleChild.html
<template>
<div class="commonCss">TEST</div>
</template>
commonStyleChild.js
import { LightningElement } from "lwc";
export default class CommonStyleChild extends LightningElement {}
commonStyleChild.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>52.0</apiVersion>
<isExposed>false</isExposed>
</LightningComponentBundle>
ローカルで動作確認
- commonStyleChild 中に右クリックし、
SFDX:Preview Component Locally
を押下する

Use Desktop Browser
を選択する

- サーバを立ち上げて、ブラウザを自動的に開く
