HTML Templates & Slots
By the end of this lesson you will be able to build a reusable card layout whose header, body and footer are filled by whoever uses it. You will use named and default slots, fallback content, the ::slotted() selector, the slotchange event and the slot methods that tell you what was placed where. You will also write the same card in plain HTML with declarative shadow DOM.
What you should know first: Template Element, Shadow DOM Fundamentals and Web Components Introduction, which showed a first named slot.
How slots work
A shadow root decides the layout of a component. The page decides the content. Slots join the two.
Think of a steel thali in a South Indian restaurant. Each katori has a fixed place: sambar here, rasam there, curd at the edge. The server puts each dish into its own katori, and the rice goes in the big open space in the middle. If the kitchen has no payasam today, that katori holds a small sweet instead. In this picture:
- the thali is the shadow tree;
- each labelled katori is a named slot,
<slot name="footer">; - the open middle is the default slot, a
<slot>with no name; - the dishes are the host's children, sent to a katori with
slot="footer"; - the substitute sweet is fallback content: whatever you write inside
<slot>...</slot>.
The most important fact: slotted children never move. They stay in the light DOM as ordinary children of the host. Page CSS still applies to them, and document.querySelector() still finds them. The browser only renders them at the slot's position. The combined picture that you see on screen is called the flat tree.
The assignment rules
- A child with
slot="footer"goes into<slot name="footer">. - Children without a
slotattribute, including text nodes, go into the default slot. - Only direct children of the host can be slotted. A
slotattribute on a grandchild does nothing. - Several children can share one slot; they appear in source order.
- A child whose slot name matches no slot is not rendered at all.
- Fallback content shows only when nothing is assigned to that slot.
The text-node rule surprises people. If your markup has line breaks between the host's tags, those whitespace text nodes are assigned to the default slot, so its fallback never appears. Fallback content works best in named slots.
Styling slotted content
Inside the shadow tree, ::slotted(selector) styles elements placed in a slot. Three limits apply:
- It takes one simple (compound) selector, such as
::slotted(h2)or::slotted(.note). - It matches only the top-level slotted elements, not their descendants.
::slotted(em)will not reach an<em>inside a slotted paragraph. - Page styles win. If the page sets a colour on the slotted element and the component also does, the page's rule applies, because the content belongs to the page.
Slotted content also inherits from where it is rendered. If the shadow tree wraps the default slot in <div class="body"> with color: #37474f, slotted paragraphs get that colour unless the page says otherwise. The <slot> element itself has display: contents, so it draws no box; style a wrapper around it instead.
Step 1: a reusable card layout
A school in Kochi wants notice cards with three regions: a header, a body and an optional footer. You will build it in four steps.
Step 1a: write the layout once in a <template>. It holds the shadow styles and three slots. The header slot has fallback text "Notice".
Step 1b: clone it into each card's shadow root. This is exactly the cloning from the Template Element lesson, but the copy goes into a shadow root instead of the page.
Step 1c: hide the footer when it is empty. A footer with only a border line looks broken. The script checks assignedNodes() on the footer slot and listens for slotchange, which fires whenever the slot's assigned nodes change.
Step 1d: use the card three times with different content.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Card layout with slots</title>
<style>
body { font-family: system-ui, sans-serif; }
.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 12px; }
info-card a { color: #6a1b9a; } /* page style for slotted content */
</style>
</head>
<body>
<h1>Kochi Public School notices</h1>
<div class="cards">
<info-card>
<h2 slot="header">Sports day</h2>
<p>Sports day is on Saturday at the main ground. Wear your house colours.</p>
<a slot="footer" href="#sports">See the events list</a>
</info-card>
<info-card>
<h2 slot="header">Library week</h2>
<p>Please return all borrowed books by Friday.</p>
</info-card>
<info-card>
<p>The canteen will serve millet snacks this month.</p>
<span slot="footer">Posted by the canteen committee</span>
</info-card>
</div>
<template id="info-card-template">
<style>
:host { display: block; border: 1px solid #cfd8dc; border-radius: 10px; overflow: hidden; }
header { background: #e0f2f1; padding: 8px 12px; }
.body { padding: 8px 12px; color: #37474f; }
footer { border-top: 1px solid #cfd8dc; padding: 6px 12px; font-size: 0.9rem; }
::slotted(h2) { margin: 0; font-size: 1.05rem; }
::slotted(p) { margin: 0 0 6px; }
</style>
<header><slot name="header"><strong>Notice</strong></slot></header>
<div class="body"><slot></slot></div>
<footer><slot name="footer"></slot></footer>
</template>
<script>
const cardTemplate = document.querySelector("#info-card-template");
class InfoCard extends HTMLElement {
constructor() {
super();
const root = this.attachShadow({ mode: "open" });
root.append(cardTemplate.content.cloneNode(true)); // Step 1b
const footerSlot = root.querySelector('slot[name="footer"]');
const footer = root.querySelector("footer");
const update = () => { footer.hidden = footerSlot.assignedNodes().length === 0; };
footerSlot.addEventListener("slotchange", update); // Step 1c
update();
}
}
customElements.define("info-card", InfoCard);
</script>
</body>
</html>You should see three cards. "Sports day" has all three regions and a purple link, from the page's own style. "Library week" has no footer line, because the footer slot is empty and the script hid it. The canteen card has no header child, so the fallback "Notice" appears in bold. The body text is grey-blue in all three, inherited from the .body wrapper in the shadow tree.
The slot JavaScript API
| API | What it gives you |
|---|---|
slot.assignedNodes() | Nodes assigned to the slot, including text nodes |
slot.assignedElements() | Only the assigned elements |
slot.assignedNodes({ flatten: true }) | Also follows nested slots, and returns the fallback content when nothing is assigned |
element.assignedSlot | The slot an element is rendered in, or null |
slotchange event | Fires on a slot when its assigned nodes change |
Two details about slotchange. It fires when children are added, removed or get a different slot value, but not when the text inside an already slotted element changes; use a MutationObserver for that. It bubbles inside the shadow tree but is not composed, so the page never hears it directly.
Step 2: a cart summary that counts its slotted items
The shop page owns the cart items as plain paragraphs with a data-price. The component reads them through assignedElements(), shows the total in rupees, and tells the page with its own event. Because that event is dispatched on the host, which lives in the light DOM, it does not need composed.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cart summary with slotchange</title>
</head>
<body>
<h1>Lucknow Gadget Bazaar</h1>
<cart-summary id="cart">
<p slot="item" data-price="1299">Bluetooth speaker</p>
<p slot="item" data-price="649">USB-C charger</p>
</cart-summary>
<button id="add">Add wireless mouse (₹499)</button>
<button id="remove">Remove last item</button>
<p id="info"></p>
<script>
const rupees = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR", maximumFractionDigits: 0 });
class CartSummary extends HTMLElement {
#slot;
#total;
constructor() {
super();
const root = this.attachShadow({ mode: "open" });
root.innerHTML = `
<style>
:host { display: block; border: 1px solid #ccc; border-radius: 8px; padding: 10px; max-width: 320px; }
::slotted(p) { margin: 0; padding: 4px 0; border-bottom: 1px dotted #ccc; }
.total { font-weight: bold; margin: 8px 0 0; }
</style>
<slot name="item"><p>Your cart is empty.</p></slot>
<p class="total"></p>`;
this.#slot = root.querySelector("slot");
this.#total = root.querySelector(".total");
this.#slot.addEventListener("slotchange", () => this.#update());
}
connectedCallback() { this.#update(); }
#update() {
const items = this.#slot.assignedElements();
const sum = items.reduce((total, item) => total + Number(item.dataset.price), 0);
this.#total.textContent = items.length ? `${items.length} item(s), total ${rupees.format(sum)}` : "";
this.dispatchEvent(new CustomEvent("cart-updated", {
bubbles: true,
detail: {
elements: items.length,
flattened: this.#slot.assignedNodes({ flatten: true }).length,
},
}));
}
}
customElements.define("cart-summary", CartSummary);
const cart = document.querySelector("#cart");
document.addEventListener("cart-updated", (e) => {
document.querySelector("#info").textContent =
`assignedElements(): ${e.detail.elements}, assignedNodes({ flatten: true }): ${e.detail.flattened}`;
});
document.querySelector("#add").addEventListener("click", () => {
const p = document.createElement("p");
p.slot = "item";
p.dataset.price = "499";
p.textContent = "Wireless mouse";
cart.append(p);
});
document.querySelector("#remove").addEventListener("click", () => {
const items = cart.querySelectorAll('[slot="item"]');
items[items.length - 1]?.remove();
});
</script>
</body>
</html>At first you see two items and "2 item(s), total ₹1,948". Click Add: a light DOM paragraph is appended, slotchange fires and the total becomes "3 item(s), total ₹2,447". Click Remove three times: the fallback "Your cart is empty." appears. The info line then reads "assignedElements(): 0, assignedNodes({ flatten: true }): 1", because with nothing assigned, the flattened list holds the fallback paragraph.
Declarative shadow DOM with slots
The same card can be written without any JavaScript, using a <template shadowrootmode="open"> as the host's first child. The parser builds the shadow root, and the slots work at once. This suits server-rendered pages: PHP, Laravel or Node can print the card, and it displays before any script runs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Declarative card with slots</title>
</head>
<body>
<h1>Exam corner</h1>
<info-card>
<template shadowrootmode="open">
<style>
:host { display: block; max-width: 320px; border: 1px solid #cfd8dc; border-radius: 10px; overflow: hidden; }
header { background: #fff3e0; padding: 8px 12px; }
.body { padding: 8px 12px; }
footer { border-top: 1px solid #cfd8dc; padding: 6px 12px; }
::slotted(h2) { margin: 0; font-size: 1.05rem; }
</style>
<header><slot name="header"><strong>Notice</strong></slot></header>
<div class="body"><slot></slot></div>
<footer><slot name="footer"></slot></footer>
</template>
<h2 slot="header">Practice exams</h2>
<p>Class 10 practice exams start on 2 March. Bring your admit card.</p>
<a slot="footer" href="#timetable">View the timetable</a>
</info-card>
</body>
</html>You should see the same card shape with an orange header, and there is no <script> on the page. The cost is repetition: every declarative instance carries its own copy of the template, so the server, not the browser, does the stamping. A custom element class can later add behaviour; as the Shadow DOM lesson showed, it should check this.shadowRoot first instead of attaching a new root.
Slots and accessibility
- Reading order follows the flat tree. Screen readers and the Tab key follow where content is rendered, not where it sits in your source. A footer link written first in the source is still read last if the footer slot comes last.
- Slotted elements keep their meaning. A slotted
<h2>is still a level 2 heading, so pick heading levels that fit the page, as in Component-Based HTML Development. - Slotted elements stay in the light DOM, so a page
<label for>can point at a slotted<input>. This is the simplest way around the id-reference problem from the Shadow DOM lesson.
Common mistakes
- Expecting default-slot fallback with whitespace around the children. Whitespace text nodes count as assigned.
- Putting
slot="..."on a grandchild. Only direct children of the host are slotted. - Styling deep inside slotted content with
::slotted(). It reaches only top-level slotted elements; let the page style the rest. - Waiting for
slotchangeafter editing text. It reacts to assignment changes, not text changes. - Styling the
<slot>box. It hasdisplay: contents; wrap it instead.
Interview questions
1. What is the difference between a named slot and the default slot?
A named slot, <slot name="x">, receives the host's direct children that have slot="x". The default slot, a <slot> without a name, receives all other direct children, including text nodes. Children whose slot name has no matching slot are not rendered.
2. Are slotted elements moved into the shadow DOM?
No. They remain children of the host in the light DOM, so page CSS and document.querySelector() still reach them. The browser only renders them at the slot's position in the flat tree.
3. What are the limits of ::slotted()?
It accepts a single compound selector and matches only top-level slotted elements, not their descendants. Page styles that target the same elements win over ::slotted() rules.
4. When does slotchange fire, and how do you read what is in a slot?
It fires on a slot when its assigned nodes change, for example when a child is added, removed or given a different slot value, but not when text inside a slotted element changes. assignedNodes() returns all assigned nodes, assignedElements() only elements, and { flatten: true } follows nested slots and includes fallback content.
5. When does fallback content appear?
Only when nothing at all is assigned to the slot. Because whitespace text nodes count for the default slot, fallback is most reliable in named slots.
Key points
- Slots let the shadow tree set the layout while the page supplies the content.
slot="name"sends a direct child to<slot name="name">; everything else, text included, goes to the default slot.- Slotted nodes stay in the light DOM; the flat tree only decides where they render.
::slotted()styles top-level slotted elements from inside, and page styles win.assignedNodes(),assignedElements(),assignedSlotandslotchangelet a component react to its content.- Templates plus slots give reusable layouts; declarative shadow DOM gives the same without JavaScript.
Exercise
Build a <profile-panel> for a Rohtak college's staff page. Its layout lives in a <template>: a photo slot, a name slot (fallback "Staff member"), a default slot for the bio and a contact slot in a footer. Use it for three teachers: one with everything, one without a photo, and one with no contact details. Hide the footer when the contact slot is empty, and show a small "No photo" placeholder as the photo slot's fallback. Use {{samples}}/avatar.svg for the photos.
Show solution
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Staff profiles</title>
<style>
.staff { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 12px; }
</style>
</head>
<body>
<h1>Department of Computer Science</h1>
<div class="staff">
<profile-panel>
<img slot="photo" src="https://course.ethicscomputer.in/assets/samples/avatar.svg" alt="Portrait of Dr Meera Sharma" width="64" height="64">
<h2 slot="name">Dr Meera Sharma</h2>
<p>Teaches databases and guides final-year projects.</p>
<a slot="contact" href="mailto:meera@example.com">meera@example.com</a>
</profile-panel>
<profile-panel>
<h2 slot="name">Kabir Singh</h2>
<p>Runs the programming lab and the coding club.</p>
<a slot="contact" href="mailto:kabir@example.com">kabir@example.com</a>
</profile-panel>
<profile-panel>
<img slot="photo" src="https://course.ethicscomputer.in/assets/samples/avatar.svg" alt="Portrait of Isha Verma" width="64" height="64">
<h2 slot="name">Isha Verma</h2>
<p>Teaches web design in the first year.</p>
</profile-panel>
</div>
<template id="profile-template">
<style>
:host { display: block; border: 1px solid #ddd; border-radius: 10px; padding: 10px; }
.top { display: flex; gap: 10px; align-items: center; }
.placeholder { display: grid; place-items: center; width: 64px; height: 64px; background: #eee; border-radius: 50%; font-size: 0.75rem; }
::slotted(img) { border-radius: 50%; }
::slotted(h2) { margin: 0; font-size: 1.05rem; }
footer { border-top: 1px solid #eee; margin-top: 8px; padding-top: 6px; }
</style>
<div class="top">
<slot name="photo"><span class="placeholder">No photo</span></slot>
<slot name="name"><strong>Staff member</strong></slot>
</div>
<slot></slot>
<footer><slot name="contact"></slot></footer>
</template>
<script>
const profileTemplate = document.querySelector("#profile-template");
class ProfilePanel extends HTMLElement {
constructor() {
super();
const root = this.attachShadow({ mode: "open" });
root.append(profileTemplate.content.cloneNode(true));
const contact = root.querySelector('slot[name="contact"]');
const footer = root.querySelector("footer");
const update = () => { footer.hidden = contact.assignedElements().length === 0; };
contact.addEventListener("slotchange", update);
update();
}
}
customElements.define("profile-panel", ProfilePanel);
</script>
</body>
</html>The photo and name slots are named, so their fallbacks work even with whitespace in the markup. Kabir's card shows the "No photo" circle, and Isha's card has no footer because its contact slot has no elements. All the content, including alt text, stays in the light DOM where the page controls it.
Quick Quiz
1. A host contains <div><span slot="title">Hi</span></div>. Where does the span render?
The slot attribute only works on direct children of the host; the div goes to the default slot and takes the span with it.
2. What does slot.assignedNodes({ flatten: true }) return for a named slot with no assigned children?
With flatten: true, an empty slot returns its fallback nodes.
3. A page rule sets info-card h2 { color: purple; } and the component has ::slotted(h2) { color: teal; }. What colour is the slotted heading?
For normal rules, page styles beat ::slotted() rules on slotted elements.
4. Which change fires slotchange?
slotchange reacts to changes in which nodes are assigned, not to text edits or styling.
Learn HTML with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
