Sub topic 6
The CSS file and style scoping
This chapter assumes you can read basic CSS selectors and the HTML and JavaScript files of a component, as covered in the earlier chapters on the template and the class. Here you learn what the CSS file does, how its rules are scoped to one component, and where that scoping surprises people.
What the CSS file does
The CSS file is optional. It sits in the bundle next to the other files and shares the bundle's name, so the greetingCard component uses greetingCard.css. If the file exists, the framework loads it automatically. You never import it from the JavaScript file and you never add a <link> tag to the template.
.greeting {
color: #032d60;
font-weight: bold;
}This rule matches the paragraph in greetingCard.html:
<template>
<lightning-card title="Greeting">
<p class="greeting">Hello, {name}!</p>
</lightning-card>
</template>The link between the two files is the class name. The template declares class="greeting", and the stylesheet selects .greeting. The class file plays no part in this link. The CSS file only styles what the template renders.
How scoping works
Styles in a component's CSS file apply only to that component's template. A rule such as p { color: red; } in greetingCard.css does not turn paragraphs red in a parent component, a sibling, or elsewhere on the page. The reverse also holds. A global p rule on the page does not reach into the component's own paragraphs, apart from inherited properties, covered below.
This works because Lightning web components use shadow DOM. Each component renders into its own shadow tree, which is a separate DOM subtree attached to the component's host element. The browser's style matching stops at the boundary of that tree. In Lightning Experience the platform uses a synthetic shadow implementation. It imitates native shadow DOM so older browsers behave the same way, and for stylesheets the result is the same: selectors do not cross the boundary.
What scoping gives you
- You can use short, generic class names like
.titleor.card-bodywithout worrying about collisions with other components. - Changing a component's CSS cannot break another component's appearance.
- You can reason about a stylesheet by reading only the one template it belongs to.
What scoping blocks
Scoping also means some things you may expect to work do not.
A parent cannot style a child's internals
Suppose parent.css contains this rule:
.greeting {
color: red;
}If .greeting is inside the child's template, the rule has no effect. The parent's stylesheet does not reach into the child's shadow tree. The parent can style the child's host element, meaning the custom element tag itself, because that element lives in the parent's template:
c-greeting-card {
display: block;
margin-bottom: 1rem;
}This rule affects the outer box of the child, such as its display mode and spacing. It cannot affect what the child renders inside.
A child cannot style its parent
A child's CSS file only ever matches elements in its own template. There is no selector that climbs out.
The `:host` selector styles the component's own host element
Inside a component's own CSS file, :host refers to the host element, which is the <c-greeting-card> tag in the parent's markup. This is how a component sets its own outer display mode:
:host {
display: block;
}Custom elements default to display: inline, so many components set :host { display: block; } to behave like a normal block box. Without it, margins and widths on the host can behave in ways that surprise you.
Slotted content belongs to the parent
When a parent passes markup into a child's <slot>, that markup is part of the parent's template. The parent's CSS styles it, and the child's CSS does not. The child can target slotted elements with ::slotted(), but only for simple selectors, and support differs between synthetic and native shadow. Prefer styling the slotted content in the parent.
Inheritance still crosses the boundary
Scoping stops selectors. It does not stop CSS inheritance. Properties that inherit by default, such as color, font-family, font-size, and line-height, pass from a parent into the child's shadow tree. If a parent sets color: red on the child's host element, text inside the child that does not set its own color shows up red.
This is why a component can look different depending on where it is placed, even though no outside selector reached into it. Properties that do not inherit, such as margin, border, and background, do not pass through.
Styling with design tokens and CSS custom properties
CSS custom properties, also called CSS variables, are inherited, so they cross the shadow boundary. This is the supported way to let a parent adjust a child's look. The child reads a variable with a fallback, and the parent sets it on the host element.
/* greetingCard.css */
.greeting {
color: var(--greeting-color, #032d60);
}/* parent.css */
c-greeting-card {
--greeting-color: #c23934;
}If the parent sets nothing, the child falls back to #032d60. The variable name is a contract between the two components, so document it when you build a reusable component.
Salesforce also provides styling hooks, which are CSS custom properties of the form --slds-c-* that Lightning base components expose for customization. Check the component reference for the hooks a given base component supports. Overriding a base component's internal class names (for example, a class inside lightning-button) does not work, because those classes are inside that component's shadow tree.
Applying styles dynamically
The CSS file holds static rules. To change appearance at runtime, change the class names in the template and let the stylesheet respond. A getter in the class can compute the class string:
import { LightningElement, api } from 'lwc';
export default class GreetingCard extends LightningElement {
@api name = 'World';
@api highlighted = false;
get greetingClass() {
return this.highlighted ? 'greeting highlight' : 'greeting';
}
}<template>
<lightning-card title="Greeting">
<p class={greetingClass}>Hello, {name}!</p>
</lightning-card>
</template>.greeting {
color: #032d60;
font-weight: bold;
}
.highlight {
background-color: #fef3c7;
}Here the three files each do one job. The class decides which names apply, the template attaches them, and the stylesheet defines how those names look.
Selector limits to know
Some selectors do not behave as they would in plain HTML, because of the component boundary.
- IDs: The framework rewrites
idvalues in templates to keep them unique per component instance. A CSS rule such as#title { ... }will not match reliably. Use classes or attribute selectors for styling. - Selectors reaching outward:
body .greetingor.page-wrapper .greetingfail, because the ancestor is outside the shadow tree. - Child component internals:
c-child .innerfails for the same reason, since.inneris in the child's tree. - Selectors across the host: Use
:hostand:host(.some-class)to react to the component's own host element.:host-context()is not supported.
Sharing CSS between components
A component can import another component's stylesheet with @import. The shared module is a bundle that holds only a CSS file named after the folder, and you refer to it by module name, as in @import 'c/sharedStyles';. A later chapter covers this in detail. The key point for scoping is that the imported rules apply to the importing component's template, not globally.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| A parent's rule does not affect text inside a child | The selector cannot cross the shadow boundary | Expose a CSS custom property in the child |
| A rule on `#title` has no effect | IDs are rewritten per instance | Select by class |
| A component's margin or width is ignored | The host element is `display: inline` | Add `:host { display: block; }` |
| A child looks different on different pages | Inherited properties like `color` or `font-family` come from the parent | Set those properties explicitly in the child |
| A global `.slds-*` override has no effect on a base component | The base component's internals are scoped | Use styling hooks (`--slds-c-*`) |
| The CSS file seems ignored | File name does not match the folder name, or case differs | Rename it to `<folderName>.css` |
Testing styles
Jest tests render components in a simulated DOM and generally do not apply your CSS files, so they are poor at checking visual results. Test the class names the component applies instead of computed colors:
import { createElement } from 'lwc';
import GreetingCard from 'c/greetingCard';
describe('c-greeting-card styling', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('adds the highlight class when highlighted', () => {
const element = createElement('c-greeting-card', { is: GreetingCard });
element.highlighted = true;
document.body.appendChild(element);
return Promise.resolve().then(() => {
const p = element.shadowRoot.querySelector('p');
expect(p.classList.contains('highlight')).toBe(true);
});
});
});Check the actual appearance in a scratch org or sandbox.
Summary of the rules
- The stylesheet must be named
<folderName>.cssand sits in the bundle root. - It is loaded automatically and applies only to the component's own template.
- Selectors cannot cross the shadow boundary in either direction.
- Inherited properties and CSS custom properties do cross it.
- Use
:hostfor the component's outer element and classes, not IDs, for everything else.
Exercise
A parent component's CSS contains .greeting { color: red; }. The .greeting paragraph is inside the child component c-greeting-card's template. The text stays dark blue. Why, and what is the supported way to let the parent change that color?
Show answer
The parent's stylesheet applies only to the parent's own template, and its selectors cannot cross the child's shadow boundary, so .greeting inside the child is never matched. The child should read a CSS custom property with a fallback, for example color: var(--greeting-color, #032d60); in greetingCard.css. The parent then sets c-greeting-card { --greeting-color: red; }, because custom properties are inherited through the shadow boundary.
Exercise
You add c-badge to a page, and the margin you set on it in its own CSS file seems to behave strangely. What rule would you add to badge.css, and why?
Show answer
Add :host { display: block; } (or inline-block if it should sit in a line). Custom elements are display: inline by default, so vertical margins and widths on the host behave unexpectedly until you set a display mode. :host selects the component's own host element from inside its own stylesheet.