CSS pseudo-class - :host-context()
CSS :host-context() pseudo-class selector allows you to style a custom element differently depending on where it is used in the DOM, based on the classes or attributes of its ancestor elements.
The :host-context() pseudo-class function has no effect when used outside a shadow DOM.
Syntax
:host-context(<compound-selector>) {
/* ... */
}
The :host-context() is not supported by Firebox and Safari Browser.
CSS :host-context Example
The following example demonstrates how to use the :host-context() pseudo-class to style a custom element differently depending on its context in the DOM −
<html>
<head>
<style>
div {
background-color: yellow;
}
</style>
</head>
<body>
<div>
<h3>Tutorialspoint CSS - <a href="#"><context-span>:host-context()</context-span></a></h3>
<p>CSS <context-span>:host-context()</context-span> pseudo-class selector allows you to style a custom element differently depending on where it is used in the DOM, based on the classes or attributes of its ancestor elements.</p>
</div>
<script>
class HostContext extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: 'open' });
const styleElement = document.createElement('style');
styleElement.textContent = `
:host-context(div) {
color: blue;
background-color: violet;
border: 3px solid red;
}
:host-context(div)::after {
content: ":host-context()";
}`;
shadowRoot.appendChild(styleElement);
}
}
customElements.define('context-span', HostContext);
</script>
</body>
</html>