:host-context() CSS Pseudo Class


The :host-context() pseudo-class is a powerful selector in CSS that allows you to apply styles to an element based on whether its parent element, or any ancestor up the DOM tree, matches a specific condition. This condition is defined using a CSS selector inside the :host-context() function.

Here's a brief breakdown of how it works:

  1. Syntax: :host-context(selector) { /* styles */ }

  2. Usage: This pseudo-class is typically used within the context of web components or shadow DOM. It helps you style an element based on the context of its container or ancestors, rather than just the element itself.

  3. Matching Condition: The selector inside :host-context() specifies the condition that must be met by any ancestor element for the styles within the block to be applied. If the condition is true for any ancestor, the styles will apply to the element.

  4. Example: Suppose you have a custom web component <my-element> inside a shadow DOM. You want to style it differently if it's placed within an element with the class .theme-dark. You can achieve this as follows:
    :host-context(.theme-dark) {
    background-color: black;
    color: white;

    In this example, if any ancestor of <my-element> has the class .theme-dark, the background will be black, and the text color will be white.

The :host-context() pseudo-class is particularly useful in the context of encapsulated web components, allowing you to create styles that respond to the environment in which they are placed, making your components more versatile and adaptable.


:host-context(<compound-selector>) {
  /* ... */


Sorry, no example yet!

Browser Support

The following table will show you the current browser support for the CSS :host-context() pseudo class.

Edge Chrome Firefox Opera Safari
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview

Last updated by CSSPortal on: 1st October 2023