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>
廣告
© . All rights reserved.