::part()

翻译正在进行中。

该 ::part CSS 伪元素 表示在 阴影树 任何匹配 part 的属性。

custom-element::part(foo) {
  /* 样式作用于 `foo` 部分 */
}

语法

::part( <ident>+ )

示例

HTML

<template id="tabbed-custom-element">
<style type="text/css">
*, ::before, ::after {
  box-sizing: border-box;
  padding: 1rem;
}
:host {
  display: flex;
}
</style>
<div part="tab active">Tab 1</div>
<div part="tab">Tab 2</div>
<div part="tab">Tab 3</div>
</template>

<tabbed-custom-element></tabbed-custom-element>

CSS

tabbed-custom-element::part(tab) {
  color: #0c0dcc;
  border-bottom: transparent solid 2px;
}

tabbed-custom-element::part(tab):hover {
  background-color: #0c0d19;
  border-color: #0c0d33;
}

tabbed-custom-element::part(tab):hover:active {
  background-color: #0c0d33;
}

tabbed-custom-element::part(tab):focus {
  box-shadow: 
    0 0 0 1px #0a84ff inset, 
    0 0 0 1px #0a84ff,
    0 0 0 4px rgba(10, 132, 255, 0.3);
}

tabbed-custom-element::part(active) {
  color: #0060df;
  border-color: #0a84ff !important;
}

JavaScript

let template = document.querySelector("#tabbed-custom-element");
globalThis.customElements.define(template.id, class extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.appendChild(template.content);
  }
});

结果

规范

规范 状态 注释
Shadow Parts
::part
Working Draft 初始定义.

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
::partChrome Full support 73Edge Full support 79Firefox Full support 72
Full support 72
No support 69 — 72
Disabled
Disabled From version 69 until version 72 (exclusive): this feature is behind the layout.css.shadow-parts.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.
IE No support NoOpera Full support 60Safari Full support 13.1WebView Android Full support 73Chrome Android Full support 73Firefox Android No support NoOpera Android Full support 52Safari iOS Full support 13.4Samsung Internet Android Full support 11.0

Legend

Full support  
Full support
No support  
No support
User must explicitly enable this feature.
User must explicitly enable this feature.

相关阅读