CSS - 偽類 :host



CSS 偽類選擇器:host主要用於在元件的影子 DOM 內樣式化宿主元素或 Web 元件的容器。Web 元件是使用 HTML、JavaScript 或 CSS 定義和構建的自定義元素。這些元件是可重用的。

當使用偽類:host進行樣式化時,它會目標指向承載 Web 元件的元素,而不是目標指向影子 DOM 內的元素本身。這有助於 Web 元件內樣式的封裝,並防止它們洩漏到其他元素或受外部樣式的影響。

在影子 DOM 外使用:host偽類無效。

語法

:host {
   /* ... */ 
}

CSS :host 示例

這是一個:host偽類的示例,其中使用 JavaScript 定義了一個自定義元素,並使用:host偽類對其進行樣式化

<html>
<head>
<style>
   li {
      padding: 3px;
   }
   body {
      font-size: 1em;
      background-color: peachpuff;
   }

</style>
</head>
<body>
    <h1><sample-span>:host</sample-span> pseudo-class</h1>
    <ul>See the list:
    <li><sample-span>Web component - Custom element</sample-span></li>
    <li><sample-span>Host element</sample-span></li>
    <li><sample-span>HTML, JS, CSS</sample-span></li>
    </ul>
   <script>
   class SampleSpan extends HTMLElement {
    constructor() {
    super();

    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 = `
       :host { background-color: yellow; padding: 2px 5px; color: blue; }
       :host { border: 2px solid red;}
    `;
 }
 }

    // Define the new element
    customElements.define('sample-span', SampleSpan);
   </script>
</body>
</html>
廣告
© . All rights reserved.