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.