- Home
- /
- Tutorials
- /
- HTML Tutorial
- /
- HTML <slot> Tags
HTML Tags
HTML <slot> Tags
The slot tag is a placeholder inside a Web Component. The component defines where the slots are; whoever uses the component fills them with their own content, like a template with gaps for the title and the text.
Slots only work inside a shadow DOM, the private inner structure of a custom element. The template that holds the component's markup is covered in the template tag.
Syntax
html
<slot name="slotName">Default content</slot>| Attribute | What it does |
|---|---|
| name | The slot's name. Content with slot="that-name" goes here. A slot without a name takes everything that has no slot. |
Example
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Slot Tag Example</title>
</head>
<body>
<template id="user-card">
<style>
div {
border: 1px solid #ccc;
padding: 10px;
border-radius: 5px;
width: 200px;
font-family: Arial, sans-serif;
}
</style>
<div>
<h3><slot name="username">Guest User</slot></h3>
<p><slot name="description">No description available.</slot></p>
</div>
</template>
<script>
class UserCard extends HTMLElement {
constructor() {
super();
const template = document.getElementById("user-card").content;
const shadow = this.attachShadow({ mode: "open" });
shadow.appendChild(template.cloneNode(true));
}
}
customElements.define("user-card", UserCard);
</script>
<user-card>
<span slot="username">Swapnil Raja</span>
<span slot="description">Web Developer & Designer</span>
</user-card>
</body>
</html>A user card appears with the name and description passed in from the page, placed into the slots called username and description. Remove one of the spans and run it again: that slot falls back to its default text, such as "Guest User".
How content finds its slot
Filling named slots
html
<user-card>
<span slot="username">Asha</span>
<span slot="description">Front-end developer</span>
</user-card>Each child with a slot attribute is moved, visually, into the slot with that name. The content still belongs to the page, so your page's CSS can style it, while the component's own CSS styles everything else.
Browser Support
Chrome | Edge | Firefox | Safari | Opera | IE9+ |
|---|---|---|---|---|---|
| Yes | Yes | Yes | Yes | Yes | Yes |
Supported in all current browsers, not in Internet Explorer.
Good to know
HTML <slot> Tags exercises
Fill a slot
Inside the custom element my-card put a span that says Card title and fills the slot called title.
Result
