Skip to content

Lesson 7 of 9 · 25m

Styling Shadow Components: Custom Properties, Parts, and Constructable Stylesheets

The styling contract that keeps encapsulation useful instead of hostile, including :host, ::slotted, CSS custom properties, parts, and shared stylesheets.

The common complaint is that shadow DOM makes styling impossible. More precisely, it makes uncontrolled styling impossible. The component author chooses the seams: too few and consumers fork internals; too many and you have recreated global CSS with extra steps.

Style the host from inside

:host { display: block; contain: layout style; }
:host([hidden]) { display: none; }

Custom elements are inline by default, and a surprising number of layout bugs are simply missing display: block. :host-context() can react to ancestor themes, but use it sparingly because it couples the component to host-page structure.

Custom properties are the primary API

.badge {
  padding: var(--badge-padding, 0.5rem 0.75rem);
  color: var(--badge-color, canvastext);
  background: var(--badge-surface, transparent);
}
user-badge.priority-high {
  --badge-surface: #7f1d1d;
  --badge-color: white;
}

Custom properties inherit through shadow boundaries, making them ideal for deliberate theming. Prefix names with the component, provide fallbacks, and expose dimensions consumers actually need rather than every internal CSS declaration.

::slotted is intentionally shallow

::slotted(strong) {
  font-weight: 650;
}

It matches only top-level assigned elements, not descendants inside them. That is correct ownership: deep control of light DOM content belongs to the outer document, where that content lives.

part exports precise internal hooks

<button part="trigger">Menu</button>
user-menu::part(trigger) {
  border-color: transparent;
}

Export stable semantic parts such as trigger, list, and item, not implementation-shaped names such as inner-wrapper-2. Every part is compatibility surface, so treat adding one like adding a public property.

Constructable stylesheets reduce duplication

const sheet = new CSSStyleSheet();
sheet.replaceSync(`:host{display:inline-block}button{font:inherit}`);

const root = this.attachShadow({ mode: "open" });
root.adoptedStyleSheets = [sheet];

Sharing one parsed sheet across instances avoids duplicating large style strings. Modern evergreen browser support is good, but SSR pipelines and older embedded webviews may still need a <style> fallback.

Field notes

  • Global resets do not enter shadow roots; include only the tiny reset your component needs.
  • Avoid !important unless protecting a critical state. Consumers cannot overpower it cleanly.
  • Document CSS variables and parts beside slots and events; they are public API.
  • Test animated theme changes. Inherited custom property transitions can behave differently across engines.

Was this lesson helpful?

Sign in to rate