HTML Component Styling: part and exportparts
Expose a styling hook
A part attribute names an element inside a shadow tree for external styling. The ::part() pseudo-element selects exposed parts on a shadow host. It does not expose every internal descendant. Multiple space-separated part names can identify the same element.
<style>#host::part(label) { color: blue; }</style><div id="host"></div><script> const root = document.querySelector("#host").attachShadow({mode: "open"}); root.innerHTML = ``;</script>Only the exposed label receives the blue color.
Forward a part through nested hosts
A part is exposed across its immediate shadow boundary. To expose it through an enclosing shadow root, place exportparts on the nested host. The mapping inner: outer renames the exposed hook for consumers of the outer host. This is useful when the internal component is an implementation detail.
<style>#outer::part(title) { color: purple; }</style><div id="outer"></div><script> const outer = document.querySelector("#outer").attachShadow({mode: "open"}); outer.innerHTML = ``; const inner = outer.querySelector("#inner").attachShadow({mode: "open"}); inner.innerHTML = ``;</script>The outer title hook styles the nested label.
Combine parts and inherited tokens
CSS custom properties can provide values across the host boundary, while part names expose selected elements. var(--accent, navy) uses the custom property or a fallback. This is a separate mechanism from ::part; document the supported names and avoid exposing all implementation details.
<style> #host { --accent: teal; } #host::part(label) { font-weight: bold; }</style><div id="host"></div><script> const root = document.querySelector("#host").attachShadow({mode: "open"}); root.innerHTML = ``;</script>The label becomes teal and bold through two separate styling mechanisms.
Common mistakes and practice
Treat part names and theme tokens as a public contract. Do not assume a part selector can freely traverse additional shadow boundaries. Test both default and customized styles.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTML Component Styling: part and exportparts — Knowledge Check
Apply the components concepts taught in this lesson.
What exposes an internal element for outside styling?
Which CSS selector targets an exposed label?
Where is exportparts placed?
What does label: title do in exportparts?
Can inherited CSS custom properties cross the host boundary?