Styling Web Components: :host, ::slotted(), ::part() and :state()
How CSS works with shadow DOM: encapsulation and what crosses it, :host and :host(), ::slotted(), ::part() and exportparts, custom properties as a theming API, :state() and :defined, and how the cascade orders inner and outer styles.
kvi5hnuCode Sprout team member10 min readOn this page
Web components are custom HTML elements, such as <book-card> or <star-rating>, built with JavaScript. Most of them use a shadow DOM: a separate, hidden tree of elements attached to the custom element, with its own stylesheet. Shadow DOM gives components real style encapsulation: page styles don't leak in, and component styles don't leak out. This article explains what that means for CSS, and the selectors designed for crossing the boundary on purpose.
Shadow trees in brief
A component's shadow tree is attached to an ordinary element, the shadow host. The children written in the page's HTML are the light DOM. Slots in the shadow tree decide where those children appear.

Shadow roots are usually created by scripts with attachShadow(), but HTML can declare one directly with declarative shadow DOM, a <template shadowrootmode="open"> as the host's first child. The examples below use it, so they work without scripts:
h2 { color: #b3261e; text-decoration: underline; } /* page style */
p { font-family: system-ui, sans-serif; }
The page's h2 rule doesn't reach the heading inside the shadow tree, and the component's h2 rule doesn't touch the page heading. The paragraph is a child of <book-card> in the page, so page styles apply to it, even though it's displayed inside the component's frame.
What does cross the boundary
Encapsulation blocks selectors, not inheritance:
- Inherited properties flow into the shadow tree from the host, as they would into any child:
color,font-family,line-height,font-sizeand the rest (article 16). Settingfont-familyon<body>styles text inside components too, unless the component overrides it. - Custom properties inherit as well. That makes them the main way to theme a component from outside: the component uses
var(--card-accent, #8a3b12), and the page sets--card-accenton the host or any ancestor. - Non-inherited properties set on the host, such as
borderormargin, style the host box itself, which is an ordinary element in the page.
/* page */
book-card { --card-accent: #1d4ed8; margin-block: 1rem; }
/* inside the component */
.frame { border-top: 4px solid var(--card-accent, #8a3b12); }
A component that wants to stop inherited page styles at its boundary can reset them on the host: :host { all: initial; } resets every property (then set display and fonts again), or reset just the ones that matter, such as :host { font: initial; color: initial; }. Custom properties aren't affected by all, so theming still works.

Only the first panel's styles fail to get in: selectors stop at the shadow boundary, while inheritance, custom properties and ::part() are the routes the component allows.
Styling the host: :host and :host()
Inside a shadow tree's stylesheet, :host selects the shadow host, the custom element itself:
:host {
display: block; /* custom elements are inline by default */
contain: content;
}
:host([variant="featured"]) { border: 2px solid var(--card-accent, #8a3b12); }
:host(:hover) { box-shadow: 0 2px 8px rgb(0 0 0 / 0.15); }
:host(:not(:defined)) { visibility: hidden; }
:host(selector)matches the host only if it matches the compound selector: an attribute, class or state on the host.:hoststyles are defaults. In the cascade, a rule in the page that targets the host wins over the component's:hostrule (for normal declarations), so a page can always overridebook-card { display: inline-block; }. For!importantdeclarations, the component's:hostrule wins.:host-context(selector), which matches when an ancestor outside the component matches, exists only in Chromium. Firefox and Safari decided not to implement it, so use custom properties or attributes on the host instead.
Styling slotted content: ::slotted()
Light DOM children that are placed in a slot can be styled from inside the component with ::slotted():
::slotted(p) { margin: 0; color: #555; }
::slotted([slot="price"]) { font-weight: 700; }
slot[name="title"]::slotted(*) { font-size: 1.25rem; }
Its limits are strict:
- It takes only a compound selector, and only matches the top-level elements placed in the slot.
::slotted(p span)is invalid, and::slotted(p)can't reach the spans inside that paragraph. - Page styles win. Slotted elements belong to the page, so a page rule for them beats
::slotted()rules for normal declarations. Components use::slotted()for defaults only. - Text in a slot can't be selected at all. It inherits from the slot, so set inherited properties such as
colororfonton theslotelement or its container. Aslotisdisplay: contentsby default, so box properties likepaddingorborderon it do nothing unless you change itsdisplay.
Firefox also supports :has-slotted, a pseudo-class for a slot that has content assigned. It's not in other browsers yet.
Styling from outside: ::part()
A component can expose elements of its shadow tree for outside styling with the part attribute. The page then targets them with ::part(name):
rating-badge::part(label) { font: 700 0.8rem system-ui, sans-serif; text-transform: uppercase; }
rating-badge::part(stars) { color: #c58b00; }
rating-badge.muted::part(stars) { color: #999; }
- Parts form a deliberate API. The component decides what's styleable, and everything else stays private.
::part()can be followed by pseudo-classes that describe the part's state, such as::part(button):hoverand::part(input):focus-visible, but not by structural pseudo-classes such as:first-child, and you can't select descendants of a part.- A
::part()rule from the page beats the component's own rule for that element, for normal declarations. - Several names select an element with all of them:
::part(tab active). A part can be followed by pseudo-elements, as in::part(label)::before, but parts can't be chained:::part(a)::part(b)is invalid. - Nested components don't expose their inner parts automatically. The middle component forwards them with
exportparts:<inner-icon exportparts="glyph, glyph: icon-glyph">, which re-exportsglyphas is and also under a new name.
Custom states: :state()
A component can define its own states, such as loading or checked, through the ElementInternals API, and CSS selects them with :state(name):
class TogglePill extends HTMLElement {
#internals = this.attachInternals();
set on(v) { v ? this.#internals.states.add("on") : this.#internals.states.delete("on"); }
}
customElements.define("toggle-pill", TogglePill);
toggle-pill:state(on) { background: #2f7d4f; color: white; } /* from the page */
:host(:state(on)) { background: #2f7d4f; } /* from inside */
Custom states behave like built-in ones such as :checked: they don't show up as attributes, and the component controls them. They've been Baseline since May 2024. Older code used a dashed syntax, :--on, which browsers no longer support.
:defined and the flash of undefined components
Before its script runs, a custom element is just an unknown inline element showing its light DOM content as plain text. :defined matches elements whose class has been registered, so you can hide or reserve space for components until they're ready:
book-card:not(:defined) {
display: block;
min-height: 12rem; /* reserve space, avoiding a layout shift */
visibility: hidden;
}
Declarative shadow DOM avoids much of this, because the shadow tree and its styles are in the HTML from the start.
Stylesheets for shadow roots
A shadow tree's styles can come from:
- A
<style>element inside the shadow root, as in the examples. <link rel="stylesheet">inside the shadow root, which loads a file.- Constructable stylesheets: a script creates
new CSSStyleSheet(), fills it withreplaceSync(), and assigns it toshadowRoot.adoptedStyleSheets. One sheet object can be shared by every instance of a component, which saves memory and parsing.
Global styles such as a reset or design tokens don't apply inside shadow roots. Components either rely on inheritance and custom properties, or adopt a shared stylesheet.
How the cascade orders inner and outer styles
When page rules and component rules both apply to the same element (the host, a slotted element or a part), the cascade compares their context before specificity (article 17):
| Declarations | Winner |
|---|---|
| normal | the outer context, the page |
!important | the inner context, the component |
That's why the page can always override a component's defaults, while a component can lock down something essential with !important. Within the shadow tree, the usual specificity and order rules apply.
What's current
- Shadow DOM styling (
:host,::slotted(),::part(),exportparts) has worked in all browsers since 2020. - Declarative shadow DOM (
shadowrootmode) is Baseline since February 2024. :state()is Baseline widely available since November 2026.:host-context()is Chromium only, and:has-slottedFirefox only.- Constructable stylesheets (
adoptedStyleSheets) work everywhere since 2023.
Common questions
Why don't my global styles apply inside a web component?
Selectors don't cross shadow boundaries, so a rule such as button { ... } in the page doesn't reach buttons in a shadow tree. Inherited properties and custom properties do pass through. Ask the component for parts or custom properties to style, or include shared styles in its shadow root.
How do I change the font of a component?
Set font-family on the host or an ancestor. It's inherited, so it reaches the shadow tree unless the component sets its own font. If it does, look for a custom property or a part the component documents.
Can I style elements inside a part, such as a span inside ::part(header)?
No. ::part() targets only the exposed element itself, plus state pseudo-classes on it. The component would have to expose the inner element as a part too.
Why does ::slotted(p strong) not work?
::slotted() accepts a single compound selector and only matches top-level slotted elements. Style the inner element from the page instead, since slotted content belongs to the page.
Is shadow DOM the only way to scope styles?
No. @scope (article 22), naming conventions such as BEM (article 116), and CSS Modules in build tools all scope styles without encapsulation. Shadow DOM is the only one that also stops page styles from coming in.
Summary
- Shadow DOM encapsulates styles: page selectors don't reach into a shadow tree, and component selectors don't reach out.
- Inherited properties and custom properties cross the boundary, which makes custom properties the theming API of most components.
:hostand:host()style the custom element from inside. Page rules for the host win over them for normal declarations.::slotted()styles top-level slotted elements with a compound selector, as defaults the page can override.partand::part()expose chosen elements for outside styling, andexportpartsforwards parts of nested components.:state()selects custom states set throughElementInternals, and:definedmatches registered custom elements.- For normal declarations the outer context wins, and for
!importantones the inner context wins.
Practice questions
The page and the component's shadow styles both set the component's display. Which wins, and why?
/* the page's stylesheet */
book-card { display: inline-block; }
/* inside the shadow root */
:host { display: block; }
Answer
The page's rule. Both apply to the host, and for normal declarations the outer context (the page) beats the inner context (the shadow tree), regardless of specificity. A component that must win would need !important.
You want users of a <date-picker> component to be able to change its accent color without exposing any internal elements. What should the component do?
Answer
Use a custom property with a default inside its styles, such as color: var(--picker-accent, #8a3b12), and document it. Users set --picker-accent on the element or an ancestor, and inheritance carries it into the shadow tree.
Why doesn't the rule below affect an <h2> inside a component's shadow tree, even when the component is inside .page?
.page h2 { color: red; }
Answer
Selectors in the page's stylesheets only match elements in the page's own tree. The shadow tree's <h2> isn't in it, so the selector can't reach it. If the heading has no color of its own, it can still inherit a color from the host, but only through inheritance, not through the selector.
A component exposes <button part="close">. Write page CSS that styles the button and its focus ring.
Answer
my-dialog::part(close) { border: 0; background: none; font-size: 1.25rem; }
my-dialog::part(close):focus-visible { outline: 2px solid #8a3b12; outline-offset: 2px; }
State pseudo-classes such as :focus-visible and :hover may follow ::part().
Review quiz
Test yourself on Part 2 with the CSS Part 2 review quiz.
Previous: Pseudo-Elements: ::before, ::after, ::first-line, ::marker, ::selection and More

More in CSS Course
Quiz: CSS Delicate Details
Twenty-five questions on the edge cases that surprise experienced developers: invalid custom properties, shorthands that reset values, layer order with !important, containing blocks, margin collapsing, specificity of :is() and :where(), intrinsic minimum sizes, and more, each checked in Chrome.
Quiz: CSS Interview Questions
Thirty front-end interview questions: cascade, specificity and layers, box model and margin collapsing, stacking contexts, positioning, flexbox and grid, responsive design, custom properties, performance, accessibility, modern selectors and architecture.
Quiz: CSS Course Final Exam
Thirty questions across the whole CSS course: syntax and error handling, selectors, the cascade and layers, values and units, color, the box model, backgrounds, positioning, flexbox, grid, responsive design, typography, generated content, effects, transforms, motion and architecture.
Quiz: CSS Architecture, Tooling and Debugging (CSS Part 17)
Twenty questions on modular CSS and BEM, layering a stylesheet, design tokens and theming, pattern libraries and safe refactoring, preprocessors and build tools, the at-rules reference, and debugging common CSS problems.
Discussion
Sign in to ask a question or share what you learned.