Chuyển đến nội dung

Bài 32 · Styling and Theming

Host Selectors and Adopted Stylesheets

Style the host and slotted content from inside a shadow root, then share CSS between many instances efficiently with constructable stylesheets and adoptedStyleSheets.

Styles inside a shadow root only apply inside it. So how does a component style itself (its own host element) or the light-DOM children slotted into it? CSS has dedicated selectors for exactly these jobs: :host, :host(), :host-context() and ::slotted(). Once you know them, the next question is efficiency: if a page has a thousand <x-chip> elements, each parsing its own copy of the same CSS is wasteful. Constructable stylesheets share one parsed sheet between them all.

Styling the host with :host

Inside the shadow root's <style>, :host selects the element the shadow root is attached to.

CSS
:host {
  display: block;          /* custom elements are inline by default! */
  box-sizing: border-box;
}

Setting display here is the single most common use. Custom elements are display: inline by default, which surprises many authors.

:host(selector) styles the host only when it matches something, such as an attribute or class:

CSS
:host([disabled]) { opacity: .5; pointer-events: none; }
:host([variant="primary"]) { --accent: #2563eb; }
:host(:hover) { box-shadow: 0 2px 8px rgba(0,0,0,.2); }

:host-context(selector) matches when the host or any ancestor matches (for example :host-context(.dark)), but it is not supported in every browser, so prefer custom properties or an explicit attribute for theming.

Priority: a page rule like x-card { display: none; } beats an internal :host { display: block; }. That is by design: the page always has the final say over the host.

Styling slotted content with ::slotted

Elements the page puts inside your component are light DOM children, so they are styled by the page, not by the shadow stylesheet. A shadow style can still reach them through the slot, but only the top-level slotted element:

CSS
::slotted(p) { margin: 0 0 .5em; }
::slotted(*) { font-family: inherit; }
slot[name="title"]::slotted(*) { font-size: 1.2rem; }

::slotted() takes a compound selector only: ::slotted(p) is fine; ::slotted(p span) (descendants of the slotted node) is not. Page styles still win over ::slotted rules.

:host and ::slotted together

The first paragraph gets the grey text from ::slotted(p), while the second keeps the page's red, because outer styles beat shadow styles on equal footing.

The cost of per-instance styles

Every <style> tag inside a shadow root is parsed separately for every instance. For a handful of elements this is fine; for lists with hundreds of items the memory and parsing time add up.

Constructable stylesheets

new CSSStyleSheet() creates a stylesheet object in JavaScript. Fill it with replaceSync(cssText) (or replace() for async) and then share it among shadow roots with root.adoptedStyleSheets = [sheet]. One parsed sheet, many adopters, and later changes to the sheet update every adopter at once.

One stylesheet, many shadow roots

Press the second button: every chip changes at once, because they all adopt the same sheet. Components are cheaper too: the CSS text is parsed once, however many chips exist.

Patterns for components

A typical class keeps the sheet as a static value:

JavaScript
const styles = new CSSStyleSheet();
styles.replaceSync(`/* css */`);

class MyElement extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" }).adoptedStyleSheets = [styles];
  }
}

You can also adopt several sheets (for example shared design tokens plus component styles) and add a document sheet to a shadow root: root.adoptedStyleSheets = [...document.adoptedStyleSheets, own]. In older Safari versions, adoptedStyleSheets could not be assigned a new array with push, so assign the whole array.

Importing CSS files with import sheet from "./x.css" with { type: "css" } is a CSS module script feature that returns a CSSStyleSheet. It needs a real module server, so it is shown here only as a read-only idea; the TryIt editors build the sheet from a string instead.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why does a component usually put display: block in :host?

    Unknown and custom elements default to inline, which rarely suits a component with its own box.
  2. 2. Which selector is valid for slotted content?

    ::slotted takes a compound selector and matches only the top-level slotted element.
  3. 3. What happens when the page styles a host and :host styles it too?

    Outer styles take priority over :host rules by design, so pages can override components.
  4. 4. What is the main benefit of adoptedStyleSheets?

    A constructable stylesheet is parsed once and shared, saving memory and time, and updates reach every adopter.

Summary

  • :host and :host(...) style the component's own element; :host-context() has patchy support.
  • ::slotted() styles top-level slotted light DOM nodes but loses to page styles.
  • Use new CSSStyleSheet() plus adoptedStyleSheets to share one parsed sheet among all instances.

Next: Lit and Web Component Libraries

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.