:host

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

Die :host-CSS-Pseudoklasse wählt den Shadow-Host des Shadow DOM aus, der das CSS enthält, innerhalb dessen sie verwendet wird — mit anderen Worten, dies ermöglicht es, ein benutzerdefiniertes Element aus seinem Shadow DOM heraus auszuwählen.

Hinweis: Dies hat keine Wirkung, wenn es außerhalb eines Shadow DOM verwendet wird.

Probieren Sie es aus

css
/* Selects a shadow root host */
:host {
  font-weight: bold;
}

Syntax

css
:host {
  /* ... */
}

Beispiele

Den Shadow-Host stylen

Die folgenden Codeausschnitte stammen aus unserem Host-Selectors-Beispiel (siehe es auch live).

In diesem Beispiel haben wir ein grundlegendes benutzerdefiniertes Element — <context-span> —, das Sie um Text wickeln können:

html
<h1>
  Host selectors <a href="#"><context-span>example</context-span></a>
</h1>

Innerhalb des Konstruktors des Elements erstellen wir style- und span-Elemente, füllen das span mit dem Inhalt des benutzerdefinierten Elements und das style-Element mit einigen CSS-Regeln:

js
const style = document.createElement("style");
const span = document.createElement("span");
span.textContent = this.textContent;

const shadowRoot = this.attachShadow({ mode: "open" });
shadowRoot.appendChild(style);
shadowRoot.appendChild(span);

style.textContent =
  "span:hover { text-decoration: underline; }" +
  ":host-context(h1) { font-style: italic; }" +
  ':host-context(h1):after { content: " - no links in headers!" }' +
  ":host-context(article, aside) { color: gray; }" +
  ":host(.footer) { color : red; }" +
  ":host { background: rgb(0 0 0 / 10%); padding: 2px 5px; }";

Die Regel :host { background: rgb(0 0 0 / 10%); padding: 2px 5px; } stylt alle Instanzen des <context-span>-Elements (in diesem Fall der Shadow-Host) im Dokument.

Spezifikationen

Specification
CSS Scoping Module Level 1
# host-selector

Browser-Kompatibilität

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
:host

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

Siehe auch