liveBook · Manning

:host selector

As explained in Web Component Development with Modern Libraries and Tooling

A CSS pseudo-class that selects a shadow host from within that host's shadow-tree styles.

The :host selector targets the custom element that contains a shadow DOM. Define it inside the component’s styles to control the host’s layout without styling its internal elements directly. section 3.8 section 4.2.5

Choose the component’s layout

A custom element is inline by default, so it behaves like a span. Set a more useful layout explicitly: :host { display: inline-block; width: 10rem; height: 5rem; } Use display: block or display: flex when the component should occupy its own line or arrange its contents with flex layout. section 3.8 section 4.2.5

Use :host rules to establish predictable component behavior:

  • Set display, padding, border, margin, width, or height on the custom element. section 4.2.5
  • Preserve the hidden attribute when overriding the default display value: :host([hidden]) { display: none; } section 4.2.6
  • Prefer a :host rule for shadow-DOM components because outside classes and styles do not directly style their rendered internal elements. section 3.8 section 6.3
Table 3.1 CSS display property values
display value Effect

inline

This allows an element to render within the flow of surrounding content. The width and height of the element can’t be set.

block

This causes an element to render on its own line. Content before and after the element appears on separate lines. The width and height of the element can be set.

inline-block

This is a hybrid of inline and block. Like inline, the element renders within the flow. Like block, the width and height of the element can be set.

Compare inline, block, and inline-block behavior before choosing the host’s display value. section 3.8

How Web Component Development with Modern Libraries and Tooling covers it

How deep it goes
Explains host targeting, display behavior, shadow-DOM boundaries, and the hidden-attribute override, without detailing selector internals.
Examples
Shows inline-block sizing, flex and block display rules, hidden-state styling, and a Stencil hello-world component.
What it assumes
Assumes familiarity with CSS display and custom elements while explaining shadow-DOM styling boundaries.
What you can do after
Apply it via CSS to set a component’s host layout and preserve hidden-element behavior.
How it connects
Connects custom elements, shadow DOM, CSS display, hidden attributes, and web component libraries.

Also explained in

Compare how 3 books explain :host selector →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Component Development with Modern Libraries and Tooling. The section links point to the parts of the book it draws on.