CSS伪类 - :host-context()



CSS :host-context()伪类选择器允许您根据其祖先元素的类或属性,在DOM中使用自定义元素的不同位置对其进行不同样式的设置。

在 shadow DOM 外使用 :host-context() 伪类函数无效。

语法

:host-context(<compound-selector>) {
   /* ... */
}
Firefox 和 Safari 浏览器不支持 :host-context()

CSS :host-context() 示例

以下示例演示如何使用 :host-context() 伪类根据其在 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>
广告