Basic Slot Usage: Named Content Projection
You'll learn how to use <slot> elements with names to create multiple, distinct insertion points for Light DOM content in your Shadow DOM.
The Core Idea
A named slot is a <slot> element with a name attribute that acts as a labeled placeholder in your Shadow DOM. Light DOM content can target specific slots using the slot attribute, allowing you to project different pieces of content into different locations within your component's template.
Think of it like a form with labeled boxes: your Shadow DOM template has boxes marked "header," "body," and "footer." Users of your component can place content into whichever boxes they choose by labeling their content accordingly.
How It Works
In your Shadow DOM template, define named slots:
<template id="card-template">
<div class="card">
<header>
<slot name="title"></slot>
</header>
<div class="content">
<slot name="body"></slot>
</div>
<footer>
<slot name="footer"></slot>
</footer>
</div>
</template>
Users project content by matching the slot attribute:
<my-card>
<h2 slot="title">Welcome</h2>
<p slot="body">This is the main content.</p>
<small slot="footer">© 2024</small>
</my-card>
Each piece of Light DOM content lands exactly where its corresponding named slot sits in the Shadow DOM structure. Content without a slot attribute falls into the default (unnamed) <slot>, if one exists.
Why This Matters
Named slots give you precise control over component composition. Instead of dumping all content into one location, you create a flexible, predictable API where users know exactly where their content will appear.
Key Takeaway: Named slots use the name attribute to create labeled insertion points in Shadow DOM, allowing Light DOM content to target specific locations using the slot attribute.