Working with Slots in Shadow DOM 🎭
📅
Slots (<slot>) are a special Shadow DOM mechanism that allows inserting external content (from Light DOM) into Shadow DOM. This is a key tool for building flexible and reusable components. ✔️
What are slots?
- A slot is a placeholder inside Shadow DOM where content from the external DOM is inserted.
- Enables components to accept and display user content while maintaining encapsulation.
- Slots support naming, allowing content to be inserted into specific slots.
Basic slot example
class MyElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
::slotted(*) {
color: green;
font-weight: bold;
}
</style>
<slot></slot>
`;
}
}
customElements.define('my-element', MyElement);
Usage:
<my-element>
<p>This text will appear in the slot and be green and bold</p>
</my-element>
Named slots 🎯
For more complex components, you can create multiple slots with different names. Content is inserted into slots by name using the slot attribute.
this.shadowRoot.innerHTML = `
<slot name="header"></slot>
<slot name="content"></slot>
<slot name="footer"></slot>
`;
Usage:
<my-element>
<h1 slot="header">Header</h1>
<p slot="content">Main content</p>
<footer slot="footer">Footer</footer>
</my-element>
How to style slotted content?
- Use the
::slotted()pseudo-class inside Shadow DOM to style elements passed into slots. - Limitation: inside
::slotted()only simple selectors are allowed (e.g.,p,.class), nested selectors are not supported.
Example:
::slotted(p) {
color: blue;
}
Handling events in slots 🔔
Events that happen inside Light DOM elements travel through slots and can be caught in Shadow DOM or on the host element.
This helps create complex interactions between external content and the component.
Common mistakes and tips 💡
- Remember that if a slot is not filled with content, its fallback content (if any) will be shown.
- Pay attention to correct slot naming and the
slotattribute on elements. - Use slots to make components as flexible and extensible as possible.
Summary 🎯
- Slots allow embedding external content into Shadow DOM
- Support named slots for complex structure
- You can style external content via
::slotted() - Events from Light DOM pass through slots, easing interaction
Use slots to create powerful and adaptable components! 🎭✨