Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

:host() — conditionally selecting a Shadow DOM host

The :host() pseudo-class selects a Shadow DOM host element when it matches the selector inside the parentheses. It operates in the context of that host’s shadow tree, letting host styles depend on a class, attribute, or another condition.

Version: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required

Syntax

:host(<compound-selector>) { /* declarations */ }

:host() is a functional pseudo-class used in a shadow tree’s stylesheet. It selects that tree’s host if the host matches its argument. Outside a shadow-tree context, it matches nothing. By contrast, :host requires no additional condition.

The argument is one compound selector (<compound-selector>), such as .active or .active[disabled]: its conditions concern the same element and are not separated by combinators. Do not directly supply the list .active, .pending or the selector .wrapper .active. :host(.active) tests the host, not its ancestor or descendant; .active:host is not equivalent.

The specificity of :host() is (0,1,0) plus its argument’s specificity. Thus, :host(.active) has (0,2,0), whereas :host has (0,1,0). The example reads padding-left before and after removing .active to test the change in matching.

Examples

<!doctype html>
<meta charset="utf-8">
<title>:host() test</title>
<div id="host" class="active"></div>
<pre id="result"></pre>
<script>
  const host = document.getElementById('host');
  const root = host.attachShadow({ mode: 'open' });
  root.innerHTML = `
    <style>
      :host { display: block; padding-left: 0px; }
      :host(.active) { padding-left: 12px; }
    </style>
    <span>Shadow content</span>
  `;
  const before = getComputedStyle(host).paddingLeft;
  host.classList.remove('active');
  const after = getComputedStyle(host).paddingLeft;
  document.getElementById('result').textContent = `${before}\n${after}`;
</script>

Result

12px
0px

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources