The :host Pseudo-Class
You'll learn how to style your custom element's host container from inside its shadow DOM using the :host pseudo-class selector.
Why :host Matters
When you create a shadow root for your custom element, styles inside the shadow DOM are encapsulated—they can't reach out to the page, and the page can't style into the shadow DOM. But what about styling the element itself—the host container?
The :host pseudo-class lets you select and style the shadow host (your custom element) from within the shadow DOM. Think of it like decorating the outside of a box while working from the inside.
Basic Usage
Inside your shadow DOM's <style> tag, you can target the host element:
class MyWidget extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: 'open' });
shadow.innerHTML = `
<style>
:host {
display: block;
padding: 20px;
border: 2px solid blue;
}
</style>
<p>Widget content</p>
`;
}
}
customElements.define('my-widget', MyWidget);
Now <my-widget> will have padding and a blue border, styled from within its own shadow DOM.
Conditional Styling with :host()
You can also apply styles conditionally based on attributes or classes:
:host([disabled]) {
opacity: 0.5;
pointer-events: none;
}
:host(.highlighted) {
background: yellow;
}
This allows your component to respond to its own state without breaking encapsulation.
Key Takeaway: The :host pseudo-class enables you to style your custom element container from within the shadow DOM, maintaining encapsulation while giving you control over the component's external appearance.