Slot Basics in Shadow DOM — Complete Guide
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you will learn about Slot Basics in Shadow Dom. We cover key concepts, practical examples, and best practices to help you master this topic.
Slots are placeholder elements in Shadow DOM that project light DOM content into specific positions within the encapsulated shadow tree.
What You'll Learn
- How default and named slots work
- How content is projected into slots
- How fallback content works
- How to style slotted content
Why It Matters
Slots are the only way to display host content inside a shadow tree. Without slots, any content inside the custom element would be invisible.
flowchart LR A[Shadow Tree] --> B[slot name=header] A --> C[slot default] A --> D[slot name=footer] E[Host Content] --> F[h2 slot=header] E --> G[p unnamed] E --> H[div slot=footer] F --> B G --> C H --> D
Default Slot
class DefaultSlotDemo extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
.container { border: 1px solid #ddd; padding: 16px; }
::slotted(*) { margin: 0; }
</style>
<div class="container">
<slot><p>Default fallback content</p></slot>
</div>
`;
}
}
customElements.define('default-slot', DefaultSlotDemo);
Named Slots
class NamedSlotDemo extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
.header { font-weight: bold; border-bottom: 1px solid #eee; padding: 8px; }
.body { padding: 8px; }
.footer { font-size: 0.9em; color: #666; border-top: 1px solid #eee; padding: 8px; }
</style>
<div class="header"><slot name="header">Default Header</slot></div>
<div class="body"><slot>Default Body</slot></div>
<div class="footer"><slot name="footer">Default Footer</slot></div>
`;
}
}
customElements.define('named-slot', NamedSlotDemo);
Common Mistakes
- Forgetting slots mean host children are hidden
- Using same slot name twice (only uses first)
- Not providing fallback content for empty slots
Practice Questions
- What happens to host children without a slot? They are not rendered.
- Can a shadow tree have multiple default slots? No. Only one unnamed slot is allowed.
Mini Project
Create a page layout component with header, sidebar, main, and footer slots. Style each area. Show fallback content when slots are empty.
What's Next
Lesson 8: Named Slots
← Previous
Shadow DOM and Events — Complete Guide
Next →
CSS Custom Properties in Shadow DOM — Complete Guide
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro