slot

The slot attribute in HTML is utilized in web components to create placeholder regions for inserting child elements, allowing for flexible composition and styling of components.

slot attribute

The slot global attributes assigns a slot in a shadow DOM shadow tree to an element: An element with a slot attribute is assigned to the slot created by the slot element whose name attribute's value matches that slot attribute's value.

Syntax

index.html
<slot name="slot-name"></slot>

Example

My Custom Component
This is content injected into the slot!
index.html
<template id="my-component">
  <h2>My Custom Component</h2>
  <div>
    <slot name="content"></slot>
  </div>
</template>
<my-component>
  <div slot="content">This is content injected into the slot!</div>
</my-component>

Here, the content with slot="header" will be inserted where <slot name="header"> is located in the shadow DOM.

See also

Conclusion

The slot attribute in HTML allows for dynamic content insertion within web components, making it an essential tool for customizing Shadow DOM elements. By creating designated slots, developers can inject specific content, enhancing component flexibility and reusability. It is widely used for creating modular and adaptable web components.