The slot Element
A template gives you a blueprint you can copy. But what if the people using your blueprint want to put their own content inside it: their own title, their own text, their own button? Filling in every field from JavaScript gets clumsy. The slot element solves this in a more HTML-like way. A component leaves openings, and the page author drops content into them with plain markup.
What You Will Learnโ
- What a slot is, and where it works
- The words you will meet: host, shadow root, light DOM, and slotted content
- Default slots, named slots, and fallback content
- How content is assigned, and what happens when nothing matches
- How to style and observe slotted content
- Accessibility and security points that come with slots
The Big Ideaโ
Think of a picture frame. The frame has its own look, and an opening in the middle. Whoever hangs it chooses the picture. A component is the frame, a slot is the opening, and the slotted content is the picture.
- Slot Lab
- Which Slot?
- The Code
Tomato pasta
Boil the pasta, then stir in the sauce.
The card is a real shadow root with three slots. The page author's elements stay in the normal page, and the browser only draws them inside the slots. Nothing is stored or sent.
The component has three slots: title, a default one, and footer. Where does each piece of content end up?
<h2 slot="title">Pasta</h2><p>Boil the water.</p><small slot="footer">By Ada</small><span slot="subtitle">Easy</span><div><p slot="footer">Hi</p></div>Serves four (plain text, directly inside the component)<recipe-card>
<h3 slot="title">Tomato pasta</h3>
<p>Boil the pasta, then stir in the sauce.</p>
<small slot="footer">By Ada</small>
</recipe-card>
class RecipeCard extends HTMLElement {
constructor() {
super();
const root = this.attachShadow({ mode: "open" });
// A fixed string written by you, with no visitor data in it
root.innerHTML = `
<style>
article { border: 1px solid #888; border-radius: 8px; padding: 0.75rem; }
header { font-weight: 700; }
</style>
<article>
<header><slot name="title">Untitled</slot></header>
<div><slot></slot></div>
<footer><slot name="footer"></slot></footer>
</article>`;
}
}
customElements.define("recipe-card", RecipeCard);
/* In the page: slotted content is ordinary page content */
recipe-card h3 { color: darkred; }
/* Inside the component's own styles: style top-level slotted elements */
/* ::slotted(small) { opacity: 0.8; } */
Where Slots Workโ
A slot only does something inside a shadow root. A shadow root is a private, separate bit of DOM attached to an element, which lets a component keep its own markup and styles apart from the page. You will build one properly in Web Components in HTML. For now, you only need the vocabulary:
| Word | Meaning |
|---|---|
| Host | The element the shadow root is attached to, such as recipe-card |
| Shadow root / shadow DOM | The component's private markup, where its slot elements live |
| Light DOM | The ordinary children the page author wrote inside the host |
| Slotted content | Light DOM nodes that the browser assigned to a slot |
| Flat tree | What the browser actually draws: the shadow DOM, with slotted content placed in its slots |
A slot written in an ordinary page, with no shadow root around it, does nothing special.
The key idea: slotted content stays in the light DOM. It is still part of the page. You can find it with document.querySelector, style it from the page's CSS, and it is part of any form it sits in. The browser only draws it in the slot's position.
Default and Named Slotsโ
- A
slotwithout a name is the default slot. It receives every direct child of the host that has noslotattribute, including plain text. - A
slotwith anamereceives the direct children whoseslotattribute matches that name.
<!-- Inside the component's shadow root -->
<slot name="title"></slot> <!-- gets slot="title" -->
<slot></slot> <!-- gets everything else -->
<slot name="footer"></slot> <!-- gets slot="footer" -->
Rules that explain most surprises:
- Only direct children of the host are assigned. A
slotattribute on a deeper element is ignored. The whole direct child goes to a slot, with its descendants. - Several elements can share one slot. They appear in the order they were written.
- An element with a
slotattribute that matches no slot is not drawn. It stays in the page's DOM, but nowhere visible. - Text counts. Loose text directly inside the host goes to the default slot.
Open the Slot Lab and try these. Tick the "second paragraph" box, then the "subtitle" box, and read the table. Then try the Which Slot? tab.
Fallback Contentโ
Whatever you place inside a slot is shown only when nothing is assigned to it:
<slot name="title">Untitled</slot>
If the page author provides no title, the card shows "Untitled". Good fallbacks make a component work with little or no content. Untick the title in the lab, and you see it.
Keep fallbacks short and neutral, because they appear in whatever language the page uses. See the global notes below.
Styling Slotted Contentโ
Because slotted nodes live in the light DOM, the page's CSS applies to them as usual. The component can also style them from inside, using the ::slotted() pseudo-element:
/* In the component's shadow styles */
::slotted(h3) { margin: 0; }
::slotted(*) { max-width: 100%; }
Know its limits:
::slotted()reaches only the top-level slotted elements, not their children.- If the page's own CSS and a
::slotted()rule disagree, the page's CSS wins. That lets page authors always override a component. - For anything deeper, a component can expose CSS custom properties (such as
--card-border) or parts (thepartattribute), which you will meet in the next lesson.
Check "Page CSS: colour the title red" in the lab. The page reaches into the slotted title with no special tools.
Watching and Reading Slotsโ
Slots have a small API:
const slot = root.querySelector('slot[name="title"]');
slot.assignedNodes(); // nodes assigned, including text
slot.assignedElements(); // elements only
slot.assignedNodes({ flatten: true }); // also follows slots nested in slots
someElement.assignedSlot; // which slot an element ended up in, or null
slot.addEventListener("slotchange", () => {
console.log("Title now has", slot.assignedElements().length, "element(s)");
});
slotchangefires when the assignment changes: nodes added, removed, or given a differentslotname. It does not fire when the text inside a slotted element changes.assignedSlotis how the lab tells which elements ended up nowhere. It returnsnullfor those.
Accessibilityโ
Slots help accessibility when used well, and cause trouble when used carelessly.
- Let the page author choose the heading level. A component that hard-codes an
h2inside its shadow DOM can break the page's outline. Slotting the heading, as in<h3 slot="title">, lets each page use the right level. - Slotted content keeps its meaning. A real heading, link, or button in the light DOM is announced as such.
- IDs do not cross the shadow boundary. Attributes that point at an
id, such asforon alabelandaria-labelledby, work only within the same tree. A label in the shadow DOM cannot point at an input in the light DOM, and the reverse. Keep related elements together on one side, or build the component to expose what it needs. - Form fields are best slotted. An
inputin the light DOM belongs to the page's form and submits normally. Aninputhidden inside a shadow root does not take part in the surrounding form unless the component is built specially for it. - Check the reading order. The flat tree decides what is read and tabbed through. Test with the keyboard.
Before and Without the Componentโ
Because slotted content is ordinary light DOM, a good component degrades gracefully:
- Until JavaScript defines the component, or in a browser without support, the children simply show as normal markup. A heading, a paragraph, and a note are still readable.
- You can style the not-yet-ready state with
:not(:defined)in your page CSS.
So write the light DOM as real, meaningful HTML first, such as headings, paragraphs, and links, and treat the component as an upgrade.
Slots or Templates and Data Fields?โ
| Slots | A template filled from JavaScript | |
|---|---|---|
| Content written as | Plain HTML, by the page author | Data, filled by your script |
| Works without JavaScript | Content is still there | Nothing appears |
| Best for | Reusable layouts that authors fill in | Lists built from data, such as rows from a server |
| Needs a shadow root | Yes | No |
They also work well together: a component clones a template into its shadow root, and that template contains the slots.
Checking Your Setupโ
- In DevTools, open Elements. Under the host you see
#shadow-root, and the slots inside it. Slotted elements show a small slot badge that links to their slot. - Select a slotted element, and check where it appears in the Accessibility panel.
- In the Console, run
host.shadowRoot.querySelector("slot").assignedNodes()to see the assignment. - Remove each piece of content in turn, and make sure the fallbacks look right.
- Add an element with a
slotname you did not define, and confirm it does not show. - Tab through the component with the keyboard.
- Turn off JavaScript, and see what the page author's markup looks like alone.
Best Practicesโ
- Name slots after their purpose, such as
titleandfooter. - Provide short, neutral fallback content.
- Slot headings, so page authors control the outline.
- Slot form controls, so they stay in the page's form.
- Write the light DOM as real, meaningful HTML.
- Keep the page's CSS able to override the component.
- Use
slotchangewhen your component must react to changes. - Document your slots, so authors know the names.
- Test with missing content, and with extra content.
- Test with the keyboard and a screen reader.
Quick Checklistโ
- Each slot has a clear name, or is the one default slot
- Each slot has sensible fallback content, or is meant to be empty
- Headings and form controls are slotted, not hard-coded
- The light DOM makes sense without the component
- Unmatched
slotnames are not relied on - Ids and ARIA references stay within one tree
- The component works with the keyboard and a screen reader
- Slot names are documented
Security and Privacy Notesโ
- Shadow DOM is not a security boundary. An open shadow root can be read by any script on the page, and scripts can reach inside it. Never keep secrets in a component's markup.
- Slotted content is page content. It is subject to the page's Content Security Policy, and anything inserted there is as dangerous as any other markup. If visitor text is shown in a slot, set it with
textContent. See XSS Basics. - Strip
slotattributes from untrusted HTML. If you accept visitor-written HTML (after sanitising), aslotattribute on it could place content into a part of your component, such as a footer or a banner, that you meant to be trusted. This is a layout-spoofing trick, so remove the attribute when you sanitise. - Do not build the shadow template from visitor text. Use a fixed string, or a
template, and fill values withtextContent. - Slots can reveal content. Anything in the light DOM is in the page source, even if the component hides it.
Global Audience Notesโ
- Writing direction is inherited. Slotted content follows the page's
dirandlang, and a card or other component should use logical properties such aspadding-inline-start. - Fallback text is visible to everyone, so it must be translatable. Pass it through your translation system, or use an
aria-labeland icons that work in any language. - Long and short text vary across languages. Do not set a fixed height on slotted regions.
- Let authors supply content in their own language. Slots are good for this, because the component does not impose any words.
- Headings and labels in the page's language help screen readers choose the right voice.
Common Mistakes to Avoidโ
- Expecting a slot to work without a shadow root.
- Putting the
slotattribute on a deeper element than a direct child. - Misspelling a slot name, so the content vanishes.
- Hard-coding headings inside the component.
- Expecting
label fororaria-labelledbyto cross the shadow boundary. - Hiding form controls inside shadow DOM and expecting them to submit.
- Forgetting fallback content, and showing empty boxes.
- Trying to style deep slotted content with
::slotted(). - Believing shadow DOM keeps secrets.
- Leaving
slotattributes in sanitised visitor HTML.
Practice Timeโ
- In the Slot Lab, untick every box. What does the table say, and what does the card show?
- Tick only the body paragraph. Which fallbacks remain?
- Tick the "subtitle" box. What does the line under the table say?
- Tick both paragraphs. In which slot do they appear, and in what order?
- Tick "Page CSS: colour the title red". Why can the page style slotted content?
- Complete the Which Slot? matcher.
- Open DevTools on the lab, find the
#shadow-root, and look for the slot badge on the title. - Bonus: write a component with a
headerslot, a default slot, and anactionsslot, with a fallback for each.
Quick Recapโ
Click a question to check your answer.
1. What is a slot?
An opening inside a component's shadow DOM where the page author's own content is displayed.
2. What is the difference between a default slot and a named slot?
A named slot receives direct children whose slot attribute matches its name. The default slot receives all other direct children, including text.
3. What happens to an element whose slot name matches nothing?
It is not assigned anywhere, and so it is not drawn, though it remains in the page's DOM.
4. What is fallback content?
Content inside a slot that is shown only when nothing is assigned to that slot.
5. Where does slotted content live, and why does it matter?
In the light DOM, as part of the page. So the page's CSS and scripts reach it, and form controls inside it submit with the page's form.
6. Why strip slot attributes from untrusted HTML?
They could place visitor content into a part of your component that is supposed to be trusted, such as a banner or footer.
Key Takeawaysโ
- A slot is an opening in a component where the page author's content appears.
- Default slot for the rest, named slots for the parts. Only direct children are assigned.
- Fallback content shows when nothing is assigned.
- Slotted content stays in the light DOM, so the page can style and query it.
- IDs and ARIA references do not cross the shadow boundary. Slot headings and form controls.
- Shadow DOM is not security. Use
textContent, and stripslotattributes from untrusted HTML. - Write meaningful light DOM first. The component is an upgrade.
Next up: Web Components in HTML, where you will combine templates, slots, shadow DOM, and custom elements into your own reusable tags.