::part() CSS Pseudo Element

If this site has been useful, we’d love your support! Running this site takes time and resources, and every small contribution helps us keep creating valuable content. Consider buying us a coffee to keep things going strong!

Description

The CSS ::part() pseudo-element can be used to select and style elements within a shadow tree. This is useful for styling custom elements, as it allows you to style the internal elements of the element without having to expose them to the outside world.

To use the ::part() pseudo-element, you must first add a part attribute to the element that you want to style. The value of the part attribute is the name of the element that you want to style within the shadow tree.

Syntax

custom-element::part(foo) {
  /* Styles to apply to the `foo` part */
}

Example

<template id="tabbed-custom-element">
<style>
*,
::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>

<script>
let template = document.querySelector("#tabbed-custom-element");
globalThis.customElements.define(
template.id,
class extends HTMLElement {
constructor() {
super().attachShadow({ mode: "open" }).append(template.content);
}
},
);
</script>
tabbed-custom-element::part(tab) {
color: #0c0dcc;
border-bottom: transparent solid 2px;
}

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

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

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;
}

Notes

In CSS3, pseudo-elements were denoted by two colons to make the syntax different from pseudo-classes. In CSS2, they are indicated by a single colon. Browsers generally understand both syntaxes.

Browser Support

The following table will show you the current browser support for the CSS ::part() pseudo element.

Desktop
Edge Chrome Firefox Opera Safari
7973726013.1
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
73795213.41173

Last updated by CSSPortal on: 1st October 2023