The :host selector matches the shadow root's host from a stylesheet inside that shadow tree. :host() adds a condition on the host, such as an attribute. Neither selector gives the shadow stylesheet control of arbitrary ancestors or makes every internal element available to the page stylesheet.
CSS :host: make a component variant an explicit host contract
When to use it
A shipment-status element has a regular and a compact density. Its owner sets a density attribute on the host; the component stylesheet adjusts padding and spacing only for that declared variant. The page can supply an accent through a documented custom property, but the component retains a fallback value. Keep the attribute vocabulary small and test missing or unexpected values as the regular state. A host with display: inline may not accept the width behavior expected of a card, so define its outer display deliberately. Do not query the page's DOM from inside this stylesheet to infer density from a surrounding layout. If the host contains an interactive control, resizing it must preserve a usable target and visible focus ring. Document which settings are public and which internal class names may change.
:host { display: block; color: #173441; border: 1px solid var(--shipment-accent, #315f75); padding: 1rem; }
:host([density="compact"]) { padding: .65rem; }
.status-row { display: flex; flex-wrap: wrap; gap: .75rem; }
:host([density="compact"]) .status-row { gap: .4rem; }Cost and verification
Selector matching is small compared with rendering the component's actual contents. The maintenance cost is treating private shadow classes as an external API; callers cannot reliably reach them, and changing them should not break themes. A custom property crosses the shadow boundary by inheritance, so its name and fallback become a contract. Inspect regular, compact, unknown-value, high-zoom, and forced-colors states. :host rules belong in shadow CSS; pasting them into a page stylesheet does not style the host. Check the resulting host box in the real layout rather than assuming the custom element's initial inline display is suitable.
Common Mistakes
- Do not place :host rules in an ordinary document stylesheet.
- Do not expose an unbounded list of density values without defined behavior.
- Do not shrink a control until its target or focus cue becomes unusable.
Connected lessons
- CSS Property Decisions
- CSS custom properties: share tokens without losing fallbacks
- CSS @scope: bound a component rule to a subtree
- HTML declarative shadow DOM: parse a component boundary from markup
- HTML custom elements: preserve useful text before upgrade
