Sub topic 15
Encapsulation and CSS Scoping in Practice
This chapter assumes you know basic CSS selectors and the cascade. It also assumes you have read the earlier chapters on shadow DOM and on the LWC component bundle. Here you will see how the shadow boundary affects the styles you write, and which controlled paths exist for crossing it.
What the boundary does to CSS
Every LWC component renders into a shadow root. A shadow root is a separate DOM tree attached to the component's host element. Browsers apply two rules to it:
- Selectors in a stylesheet outside the shadow tree do not match elements inside it.
- Selectors inside the shadow tree do not match elements outside it.
LWC builds on this. The component's .css file is applied only to that component's own template. A rule such as p { color: red; } in card.css affects paragraphs in the card's template. It does not affect paragraphs in the parent, in the child components, or elsewhere on the page.
A component stylesheet
The bundle files share the base name. card.css is picked up automatically, with no import.
<!-- card.html -->
<template>
<div class="card">
<h2 class="title">{title}</h2>
<slot></slot>
</div>
</template>// card.js
import { LightningElement, api } from 'lwc';
export default class Card extends LightningElement {
@api title = 'Untitled';
}/* card.css */
:host {
display: block;
margin: 0.5rem 0;
}
.card {
border: 1px solid #c9c9c9;
border-radius: 0.25rem;
padding: 1rem;
}
.title {
margin: 0 0 0.5rem;
color: var(--card-accent, #032d60);
}Class names such as .card and .title are safe because they are local. Another component can use .card for something else and the two will not collide. You do not need naming schemes such as BEM to prevent clashes between components.
Styling the host with :host
The host element is the custom element itself, for example <c-card>. Its box belongs to the parent's layout, but the component usually wants to set its own defaults, such as display. Custom elements default to display: inline, which is rarely what you want for a card. Use :host in the component's own CSS for this.
:hostmatches the host element.:host(.highlight)matches the host only when it has the classhighlight.- A rule in the parent's CSS that targets
c-cardalso works, and it takes priority over:hostrules from the child, because styles from the outer tree win over:hoststyles.
Crossing the boundary with custom properties
A parent cannot write c-card .title { ... } and expect it to work. The selector stops at the host. CSS custom properties are the supported way through, because they are inherited values, and inheritance continues across shadow boundaries.
/* parentPanel.css */
c-card {
--card-accent: #c23934;
}<!-- parentPanel.html -->
<template>
<c-card title="Overdue"></c-card>
</template>The child's .title rule reads var(--card-accent, #032d60). The parent supplies a value and the child supplies a fallback. This makes the custom properties the child reads into its public styling API. Document them as you would document @api properties. Salesforce's styling hooks in the Lightning Design System follow the same idea.
Inherited properties such as color, font-family and line-height also pass through on their own. A component that does not set a font will pick up the font of the page area it sits in.
Slotted content belongs to its owner
Content passed into a <slot> appears inside the child visually. Its styles still come from where it was written.
<!-- parentPanel.html -->
<template>
<c-card title="Notes">
<p class="note">Call the customer.</p>
</c-card>
</template>The .note rule must live in parentPanel.css, because the paragraph belongs to the parent's template. A .note rule in card.css will not match it. The child can style the slot element itself, and it can use the ::slotted(p) selector for the direct slotted elements. Support for ::slotted depends on whether native or synthetic shadow is active, so prefer owner-side styling when you can.
Queries stop at the boundary too
Encapsulation covers the DOM as well as CSS. A component looks in its own template with this.template. It cannot see inside a child's template.
// parentPanel.js
import { LightningElement } from 'lwc';
export default class ParentPanel extends LightningElement {
renderedCallback() {
// Finds the c-card host element in this component's template.
const card = this.template.querySelector('c-card');
// Returns null: .title lives in the child's shadow tree.
const title = this.template.querySelector('.title');
console.log(card !== null, title === null);
}
}If a parent needs something from a child, it should use an @api property or method. Reaching in with selectors is intentionally blocked. Events are encapsulated too. When an event crosses a shadow boundary, event.target is retargeted to the host element, so listeners outside see the child host and not its inner elements.
Native and synthetic shadow
Two implementations exist. Native shadow uses the browser's own attachShadow. Synthetic shadow is a JavaScript polyfill that emulates the same rules on browsers or pages where native shadow is not used. It has been the default in Salesforce's Lightning Experience, while the open-source LWC project supports native shadow. The behavior you rely on, scoped styles and this.template queries, is the same in both. Edge cases differ. Examples are ::slotted details, global stylesheets reaching into components in synthetic mode, and how id attributes are rewritten. Test in the environment you ship to.
Opting out with light DOM
A component can render without a shadow root.
<!-- plainList.html -->
<template lwc:render-mode="light">
<ul class="plain-list"><slot></slot></ul>
</template>// plainList.js
import { LightningElement } from 'lwc';
export default class PlainList extends LightningElement {
static renderMode = 'light';
}In light DOM, the markup joins the surrounding tree. Page styles can reach it, and its own styles are not scoped to a shadow root, so rules can leak. Choose it when you must share styles with the page or integrate with a third-party library that expects a normal DOM. Keep shadow DOM as the default.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Parent rule `c-card .title` has no effect | Selector cannot cross the shadow boundary | Expose a custom property and read it in the child |
| Component appears with zero height or inline layout | Host defaults to `display: inline` | Add `:host { display: block; }` |
| Slotted element ignores `card.css` | Slotted nodes are styled by their owner | Move the rule to the parent's CSS |
| `this.template.querySelector` returns `null` for a child's element | Child tree is private | Call an `@api` method or pass data down |
| Global stylesheet does not restyle a component | Scoping blocks it | Use custom properties or styling hooks |
Exercise
A parent template contains <c-card><span class="badge">New</span></c-card>. Where must the .badge rule go so it applies, and why?
Show answer
It must go in the parent's CSS file. The span is part of the parent's template, so the parent's stylesheet styles it even though it renders inside the child's slot. A .badge rule in card.css will not match it.
Exercise
A child component reads color: var(--panel-text, black). Write the parent CSS that makes the text navy, and explain why this works when a descendant selector does not.
Show answer
In the parent's CSS, write c-panel { --panel-text: navy; }. Custom properties are inherited, and inheritance continues through shadow roots, so the child's rule receives the value. A descendant selector such as c-panel p cannot match elements inside the child's shadow tree.