Skip to main content

HTML Tags

HTML <slot> Tags

Written by Updated

The <slot> tag is a placeholder inside a Web Component that allows developers to pass external content (light DOM) into the shadow DOM.
It helps in creating flexible and reusable custom elements where parts of the content can be dynamically replaced.

Syntax

html

<slot name="slotName">Default content</slot>

Attributes

AttributeDescription
nameDefines the name of the slot so specific content can be assigned to it.

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>

Browser Support

Chrome
Edge
Firefox
Safari
Opera
IE9+
YesYesYesYesYesYes

All major browsers support <slot> tag except of IE

Notes

  • The <slot> tag is only meaningful when used inside a shadow DOM of a Web Component.
  • You can define named slots using the name attribute and insert specific content using the corresponding slot attribute in light DOM.
  • Default slot content appears when no light DOM content is provided for that slot.

Conclusion

The <slot> tag enables content projection in Web Components, allowing external content to be inserted dynamically.
It enhances the flexibility and reusability of custom elements in modern web development.