Slot element
Create flexible content insertion points with <slot>.
What is the slot element?
A <slot> marks the place inside a component where outside content will land. The idea is: whatever the caller passes lands here. The same skeleton then works with many different contents.
Slots give web components and templates their flexibility. Write a card skeleton once, make the title a slot; each caller drops in its own title. When the slot is empty, fallback content shows instead.
Naming slots with name
You can put more than one <slot> in a skeleton. The name attribute decides which content goes where: <slot name="title">.
An unnamed slot is the default slot; all leftover content lands there. A named slot accepts only the content piece with the same name. That way title, image and footer each land in their own place.
Putting fallback content in a slot
Anything you write inside a slot becomes fallback shown when the caller passes nothing. For example <slot>No comments yet</slot> shows that text when no content arrives.
Fallback keeps the layout meaningful. An empty list can say no comments yet, a broken image can show a default icon. This stops empty components from looking broken.
Exercise Write a template with a slot
Add a <template> to body. Inside it put an <h2> (text: Card Title) and a <slot>. When the slot is empty it should show the fallback No content.
Show example solution
<body>
<template>
<h2>Card Title</h2>
<slot>No content</slot>
</template>
</body>
Test yourself
-
What is the most important feature of the slot element?
- It copies content automatically.
- It marks where outside content is inserted.
- It accepts only text, no tags.
- It is hidden when the page loads.
Show answer
It marks where outside content is inserted. — Correct. A slot marks where the caller's content will land.
-
Write the slot tag
<template> <h2>Card</h2> ____ </template>Show answer
<template> <h2>Card</h2> <slot></slot> </template> -
Match the slot terms
- slot
- content insertion point
- name
- the slot's name
- default slot
- unnamed slot
- fallback
- shown when slot is empty