Implementing Shadow DOM for Component Style Encapsulation
Shadow DOM—a browser mechanism for creating an isolated DOM subtree. External styles don't penetrate inside, internal styles don't leak outside. This enables creating components that work identically in any CSS environment.
How Shadow DOM works
Document (Light DOM)
├── <header>
├── <main>
│ └── <my-widget> ← Custom Element
│ └── #shadow-root ← Shadow Root (encapsulation boundary)
│ ├── <style> ← styles visible only here
│ └── <div class="widget">
│ └── <slot> ← Light DOM content projection
└── <footer>
Global CSS div { color: red } doesn't affect div inside shadow-root. CSS from shadow-root doesn't affect div outside.
Open and closed modes
// mode: 'open' — access to shadowRoot from outside (el.shadowRoot !== null)
const openShadow = element.attachShadow({ mode: 'open' })
// mode: 'closed' — shadowRoot === null from outside
// Used for maximum encapsulation (native browser elements)
const closedShadow = element.attachShadow({ mode: 'closed' })
In vast majority of cases mode: 'open' is used—dev tools, testing utilities and form management libraries (react-hook-form, browser forms) require shadowRoot access.
Styling from inside
class StyledCard extends HTMLElement {
constructor() {
super()
const shadow = this.attachShadow({ mode: 'open' })
shadow.innerHTML = `
<style>
/* :host — the <styled-card> element itself */
:host {
display: block;
border-radius: 12px;
overflow: hidden;
}
/* :host() with condition */
:host([variant="dark"]) {
background: #1a1a1a;
color: #fff;
}
:host([variant="light"]) {
background: #fff;
color: #111;
box-shadow: 0 2px 20px rgba(0,0,0,0.08);
}
/* :host-context() — reaction to environment */
:host-context(.dark-theme) {
background: #222;
}
.card-body {
padding: 24px;
}
.card-title {
font-size: 20px;
font-weight: 700;
margin: 0 0 12px;
}
/* ::slotted — style projected content */
::slotted(p) {
margin: 0;
line-height: 1.6;
opacity: 0.7;
}
::slotted([slot="footer"]) {
margin-top: 20px;
padding-top: 16px;
border-top: 1px solid currentColor;
opacity: 0.2;
}
</style>
<div class="card-body">
<h3 class="card-title">
<slot name="title">Title</slot>
</h3>
<slot></slot>
<slot name="footer"></slot>
</div>
`
}
}
CSS Custom Properties: bridge across Shadow DOM
The only way to pass styles inside—through CSS variables. They penetrate the Shadow DOM boundary.
/* Outside: set variables */
styled-card {
--card-bg: #f8f9fa;
--card-radius: 16px;
--card-padding: 32px;
--card-title-color: #1a1a1a;
}
/* Inside Shadow DOM: use variables with fallback */
:host {
background: var(--card-bg, #fff);
border-radius: var(--card-radius, 8px);
}
.card-body {
padding: var(--card-padding, 24px);
}
.card-title {
color: var(--card-title-color, inherit);
}
<!-- Different instances with different styles -->
<styled-card style="--card-bg: #1a0050; --card-title-color: #fff">
<span slot="title">Dark card</span>
<p>Content</p>
</styled-card>
<styled-card style="--card-bg: #e8f5e9; --card-padding: 40px">
<span slot="title">Green card</span>
<p>Content</p>
</styled-card>
CSS Parts: targeted outside styling
part attribute exposes specific elements for external styles via ::part():
shadow.innerHTML = `
<div class="wrapper" part="wrapper">
<button class="btn" part="button trigger">
<slot></slot>
</button>
<div class="dropdown" part="dropdown">
<slot name="items"></slot>
</div>
</div>
`
/* Outside — style only exposed parts */
my-dropdown::part(button) {
background: #7000ff;
color: #fff;
border-radius: 8px;
}
my-dropdown::part(dropdown) {
background: #1a1a1a;
border: 1px solid #333;
}
/* hover on part */
my-dropdown::part(button):hover {
background: #5500cc;
}
Adoptable Stylesheets (CSSStyleSheet API)
For reusing styles between Shadow DOMs without duplication:
// Create shared stylesheet once
const sharedStyles = new CSSStyleSheet()
sharedStyles.replaceSync(`
:host { box-sizing: border-box; }
*, *::before, *::after { box-sizing: inherit; }
button {
cursor: pointer;
border: none;
font: inherit;
}
`)
const typographyStyles = new CSSStyleSheet()
typographyStyles.replaceSync(`
h1, h2, h3 { font-weight: 700; line-height: 1.2; margin: 0; }
p { line-height: 1.6; margin: 0 0 1em; }
`)
// Use in components
class ComponentA extends HTMLElement {
constructor() {
super()
const shadow = this.attachShadow({ mode: 'open' })
// Adoptable stylesheets — no CSS duplication
shadow.adoptedStyleSheets = [sharedStyles, typographyStyles]
// Only component-specific styles
const localStyle = new CSSStyleSheet()
localStyle.replaceSync(`.wrapper { background: blue; }`)
shadow.adoptedStyleSheets.push(localStyle)
}
}
class ComponentB extends HTMLElement {
constructor() {
super()
const shadow = this.attachShadow({ mode: 'open' })
shadow.adoptedStyleSheets = [sharedStyles] // only basic styles
}
}
Shadow DOM and forms
Native form elements inside Shadow DOM don't participate in form.elements and don't end up in FormData. Solution via ElementInternals:
class CustomInput extends HTMLElement {
static get formAssociated() { return true }
private internals: ElementInternals
private shadow: ShadowRoot
constructor() {
super()
// formAssociated + ElementInternals allow form participation
this.internals = this.attachInternals()
this.shadow = this.attachShadow({ mode: 'open' })
}
connectedCallback() {
this.shadow.innerHTML = `
<style>
input {
width: 100%;
padding: 10px 14px;
border: 1px solid var(--border-color, #d0d5dd);
border-radius: 8px;
font: inherit;
outline: none;
}
input:focus {
border-color: var(--focus-color, #7000ff);
box-shadow: 0 0 0 3px var(--focus-ring, rgba(112, 0, 255, 0.15));
}
</style>
<input type="text" />
`
const input = this.shadow.querySelector('input')!
input.addEventListener('input', () => {
// Sync value with form
this.internals.setFormValue(input.value)
this.internals.setValidity(
input.validity,
input.validationMessage,
input
)
})
}
// Browser calls on form reset
formResetCallback() {
const input = this.shadow.querySelector('input')
if (input) input.value = ''
this.internals.setFormValue('')
}
}
customElements.define('custom-input', CustomInput)
Timeline
One component with Shadow DOM, Custom Properties and Parts — 1 day. System of 5–8 components with Adoptable Stylesheets, ElementInternals for forms and documentation — 1–2 weeks.







