Style Isolation in Shadow DOM
📅
One of the main advantages of using Shadow DOM is complete style isolation inside a component. This means CSS applied inside the Shadow Root does not affect the external document, and conversely — external styles don’t “leak” into the component. ✔️
Why is style isolation important?
- 🛡️ Prevents conflicts between styles of different parts of the application
- 🔄 Simplifies maintenance — you can change component styles without risking breaking other UI parts
- 🚀 Speeds up development by allowing you to write local CSS without worrying about global effects
How does isolation work?
Shadow DOM creates a separate DOM tree with its own style context. All CSS selectors and rules apply only inside this tree.
Example: styles inside Shadow DOM don’t affect external elements
```html
<style>
p {
color: red;
}
</style>
<my-element></my-element>
<script>
class MyElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
p {
color: blue;
font-weight: bold;
}
</style>
<p>Blue text from Shadow DOM</p>
`;
}
}
customElements.define('my-element', MyElement);
</script>
```
In this example:
- The external
<style>paints all<p>red - Inside the Shadow DOM, the
<p>is blue and bold — styles from Shadow Root override the external ones
::part and ::slotted — styling from outside
Sometimes you need to style internal parts of the component or content passed through slots:
| Pseudo-element | Description | Usage example |
|---|---|---|
::part() |
Allows styling marked parts of Shadow DOM from external CSS | <div part="button">...</div> and my-element::part(button) {} |
::slotted() |
Allows styling elements inserted into <slot> from Light DOM |
::slotted(p) { color: green; } |
Style isolation limitations ⚠️
- Styles from Light DOM do not penetrate Shadow DOM
- Styles from Shadow DOM do not apply to Light DOM or sibling elements
- Global styles like
body,htmldo not affect the Shadow Root - Use
::partand slots to interact with external styles
Tips for styling in Shadow DOM 💡
- Always include a
<style>inside Shadow Root for local styles - Use CSS Custom Properties (variables) to configure external parameters of the component
- Wrap styles in
<template>for reuse - Use
::partand::slottedfor flexible external customization
Summary 🎯
- Shadow DOM provides clean style isolation
- Allows writing CSS without fear of conflicts
- External styling control possible via
::partand::slotted - This is key to building reliable and reusable web components
Create styles that work exactly where they should! 🎨✨