What is the slot tag in HTML and How to Use It
<slot> tag in HTML is used inside web components to create placeholders where content can be inserted from outside the component. It allows developers to design reusable components with customizable parts by letting users pass in their own HTML content.How It Works
Think of the <slot> tag as a special empty box inside a web component. When you use the component, you can put your own content into this box. The component shows this content exactly where the <slot> tag is placed.
This works like a gift box with a window: the box is the component, and the window is the slot. You can put different gifts (content) inside the box, and the window will show whatever you put in.
Slots help keep components flexible and reusable because the component controls the structure and style, but the user controls the content inside the slots.
Example
This example shows a simple web component with a slot. The slot lets you add your own text inside the component.
class MyCard extends HTMLElement { constructor() { super(); const shadow = this.attachShadow({ mode: 'open' }); shadow.innerHTML = ` <style> .card { border: 2px solid #4CAF50; padding: 1rem; border-radius: 8px; font-family: Arial, sans-serif; max-width: 300px; } </style> <div class="card"> <h2>My Card</h2> <slot></slot> <!-- This is where user content goes --> </div> `; } } customElements.define('my-card', MyCard); // Usage in HTML: // <my-card> // <p>This content goes inside the slot!</p> // </my-card>
When to Use
Use the <slot> tag when building web components that need to show different content depending on where they are used. It is perfect for creating reusable UI parts like cards, modals, or tabs where the structure stays the same but the content changes.
For example, if you make a button component, you can use a slot to let users put any label or icon inside the button. This way, the button looks consistent but can show different text or images.
Key Points
- The
<slot>tag creates a placeholder inside a web component. - Content placed between the component tags fills the slot.
- Slots make components flexible and reusable.
- You can have multiple slots with names to organize content.
- Slots work only inside shadow DOM of web components.