References

Beginner-friendly references for web development, with live, editable examples.

The HTML part attribute

Global attribute Works on every element All modern browsers
In short

The HTML part attribute exposes an element inside a shadow DOM so the host page can style it with the CSS ::part() pseudo-element. It is a global attribute used when authoring web components, giving consumers controlled styling hooks across the shadow boundary.

Overview

Styles do not normally cross the shadow boundary, which protects a web component's internals but also stops consumers from theming them. The part attribute opens specific, named holes in that wall: mark an internal element with part="label" and the outside page can target it with my-component::part(label) { … }.

You can give an element several space-separated part names, and to forward parts from a nested component you use exportparts.

Values

Value
One or more space-separated part names.

Example

Live example
<!-- Inside the component's shadow DOM -->
<span part="title">Card title</span>

<!-- In the host page's CSS -->
my-card::part(title) { color: navy; }

Best practices

  • Treat each part name like a class rather than an id. Several elements can share a name, and ::part(tab selected) matches an element that carries both names, in either order, but not one with a single name.
  • Follow ::part(label) with a user-action pseudo-class such as :hover, or with ::before, but not with a structural one such as :first-child. That selector is invalid, so the whole rule is dropped, along with the other selectors in its list.
  • Expect a page's ::part() rule to beat the component's own normal declarations for that element. Inside the component, mark a declaration !important when it must hold, since inner important rules win over outer ones.
  • Change part names at run time through the part property, a token list with add(), remove() and toggle(). Toggling a name such as selected restyles the element through matching ::part() rules.
  • Closing the shadow root doesn't hide its parts. A component attached with mode: 'closed' still answers the page's ::part() rules in Chrome and Firefox, so leave the attribute off elements you don't want restyled.

Frequently asked questions

What does the part attribute do?
Exposes an element inside a shadow tree so it can be styled from outside with ::part().
How do I style inside a web component from outside?
Expose elements with the part attribute, then target them with the ::part() pseudo-element.
How do I fill a named slot?
Add slot="name" to your content so it projects into the matching <slot>.
Is part a global attribute?
Yes, it is a global attribute, so it can be set on any HTML element, within web components.