Course contentsShow
← Web Development
Lesson 2465 of 2,98244. Web ComponentsFree lesson

Conditional Host Styling with :host()

Applying styles to the host element based on selectors like classes or attributes.

Conditional Host Styling with :host()

You'll learn how to apply styles to your Web Component's host element only when it matches specific conditions like classes or attributes.

The Core Idea

In the previous lesson, you learned about :host for styling the host element itself. But what if you want to style it conditionally—only when the host has a particular class, attribute, or state? That's where :host() comes in.

The :host() pseudo-class takes a selector as an argument. Styles inside :host() only apply when the custom element's host matches that selector. Think of it as an "if statement" for your host styling—"if the host has this class, then apply these styles."

How It Works

Inside your Shadow DOM stylesheet, you can write:

:host(.highlighted) {
  background: yellow;
  border: 2px solid orange;
}

:host([disabled]) {
  opacity: 0.5;
  pointer-events: none;
}

:host(:hover) {
  box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}

The first rule applies only when <my-component class="highlighted"> exists in the Light DOM. The second applies when <my-component disabled> is present. The third responds to hover state.

Why This Matters

This allows your component to be styled from the outside via classes or attributes while maintaining encapsulation. The Light DOM can signal "modes" or states, and your Shadow DOM styles respond accordingly—without breaking the style boundary.

Key Takeaway: :host() enables conditional styling of the host element based on selectors, letting your component react to external classes, attributes, or pseudo-classes while keeping styles encapsulated.