Parts and ::part() for External Styling
You'll learn how to intentionally expose specific shadow DOM elements for styling by external CSS using the part attribute and ::part() pseudo-element.
The Core Idea
Shadow DOM encapsulation protects your component's internals from outside interference—but sometimes you want to let users customize certain pieces. The part attribute creates explicit "styling hooks" on shadow DOM elements, allowing external stylesheets to target them with the ::part() pseudo-element. Think of it like installing official access panels on a sealed appliance: you control exactly what can be modified while keeping everything else protected.
How It Works
Inside your shadow DOM, add a part attribute to any element you want to expose:
class FancyButton extends HTMLElement {
connectedCallback() {
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
button { padding: 10px; }
</style>
<button part="button-core">
<slot></slot>
</button>
`;
}
}
customElements.define('fancy-button', FancyButton);
Now external CSS can style that specific element:
fancy-button::part(button-core) {
background: linear-gradient(to right, blue, purple);
border-radius: 8px;
}
The shadow DOM's internal styles still apply, but external CSS can layer additional styling onto parts. You can name parts descriptively (part="label", part="icon") and even assign multiple parts to one element with space-separated values: part="button primary-action".
Key Takeaway: The part attribute creates controlled styling boundaries—you explicitly choose which shadow DOM elements external CSS can customize using ::part(), maintaining encapsulation while enabling intentional flexibility.