Skip to content
AITroveRead. Build. Understand.
Make this comfortable

CSS :host: make a component variant an explicit host contract

Last updated: 5 Oct 20265 min read
tutorial
BeginnerBy AITrove Editorial

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.

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.

css
: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

Related native states

css
reference
web
Storage details