HTML ยท Module 11 ยท Lesson 51 of 54

Slots & Shadow DOM

What are Slots & Shadow DOM?

  • Shadow DOM: Think of a standalone appliance like a microwave. It has its own wiring, casing, and control panel hidden inside. The style of the microwave doesn't conflict with your kitchen wallpaper, and your wallpaper doesn't change the microwave's styling. It is isolated.
  • Slots: Think of slots on the microwave. You insert your own cup or plate (your markup) into the slot, and the microwave runs its internal processes on it.
  • In Web Components:

  • Shadow DOM isolates component CSS, preventing global page styles from leaking in or component styles from leaking out.
  • <slot name="title">: Reusable placeholder markers inside component templates where users can inject their own custom HTML.
  • Why does it matter?

    Shadow DOM allows developers to build self-contained widgets (like video players, calendars, or chat boxes) that look identical on any website, regardless of what CSS stylesheet that site uses. It is the foundation of modern component-based web standards.

    How to write it

    Declare slots inside your component template:
    <template>
      <div class="header">
        <slot name="title"></slot>
      </div>
    </template>
    

    Shadow DOM Context
    <slot name="label"> Injected text

    Common Mistakes

  • Mismatched slot names: If you write <slot name="title"> in the template, but supply content using <span slot="heading">, the slot won't bind, and your content won't render. Make sure slot names match exactly!
  • Quick Reference

  • <slot name="name"> โ€” Markup placeholder slot inside templates.
  • Your Task
    Inside a Web Component template, create a `<slot>` element with the attribute `name="title"`.
    index.html
    Type code above to start the lesson.
    Live Preview