CSS - 伪元素 - ::part()



描述

CSS 中的::part()伪元素用于表示在具有匹配 part 属性的影子树中的元素;也就是说,::part()伪元素充当函数,并以part作为参数。

part属性是一个全局属性,它表示元素的 part 名称的空格分隔列表。这些 part 名称允许使用::part()伪元素选择和设置影子树中特定元素的样式。

语法

selector::part(+) { /* ... */ }

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

CSS ::part() 示例

这是一个::part()伪元素的示例。在这个例子中

  • 使用 JavaScript (new-widget) 创建了一个模板。

  • 将模板的一部分声明为 widget。

  • 将 'widget' 作为参数传递给 ::part() 伪元素,其中指定了 CSS 样式。

  • 由于 part (widget) 包含一个<p>标签,因此 CSS 样式将应用于此<p>标签。

Open Compiler
<html> <head> <style> .container { max-width: 500px; margin: 0 auto; padding: 2em; } body { font: 1em/1.618 Segoe UI, sans-serif; } new-widget::part(widget) { max-width: 300px; padding: 1em; background-color: lightgoldenrodyellow; border-radius: 20%; } </style> </head> <body> <div class="container"> <p>This paragraph is rendered as normal without any style.</p> <template id="new-widget"> <div part="widget"> <p>This paragraph is rendered as a part of the main paragraph and thus the ::part() pseudo-element is applied here.</p> </div> </template> <new-widget></new-widget> <script> let template = document.querySelector("#new-widget"); globalThis.customElements.define( template.id, class extends HTMLElement { constructor() { super() .attachShadow({ mode: "open" }) .append(template.content); } } ); </script> </div> </body> </html>
广告