CSS-38Recommended
Style web components through parts and custom properties
Style the inside of a shadow root only from the component's own stylesheet. Page styles reach it only through the custom properties and the ::part() names that the component lists.
How to do it
A shadow root fences a component's markup off from page selectors, so the page's layers and classes stop at its edge. That fence holds only while nobody works around it. Write the shadow root into the server-rendered HTML with <template shadowrootmode="open">, so the component shows its styled content before any script runs. Declarative shadow DOM has worked in every major browser since February 2024. Give each element a page may restyle a part name, and read every outside value through a custom property with a fallback. List both in the component catalogue, named with the prefix from Name custom elements with the project prefix. The component's stylesheet comes from the bundle like any other, as Write styles only in stylesheets requires.
Examples
HTML example
<bakery-basket>
<template shadowrootmode="open">
<button part="checkout" class="bakery-basket-checkout">Check out</button>
</template>
</bakery-basket>
CSS example
/* Inside the component: outside values come in through custom properties */
.bakery-basket-checkout { padding: var(--bakery-basket-padding, 0.5rem 1rem); }
/* On the page: only the listed part is styled */
bakery-basket::part(checkout) { border-radius: var(--radius-control); }
How to check
Every ::part() name in the page stylesheets matches a part attribute in a component template. Every var() in a shadow stylesheet that reads an outside property has a fallback and appears in the catalogue.
Sources
Related rules
- CSS-25 Name custom elements with the project prefix in HTML and CSS
- CSS-5 Write styles only in stylesheets in HTML and CSS
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/html-css/html-structure-and-reuse/shadow-dom-styles">Agent Wranglers HTML and CSS playbook</a>. In code you write, add a comment next to it with the same link.