Slots for Web Component Composition

Uses slot elements with named and default slots to create flexible web component templates that accept distributed content from the parent.

HtmlData Fetching

Code

htmlsnippet
44 lines
<!-- Define a custom element with slots -->
<template id="card-template">
  <style>
    .card { border: 1px solid #ccc; border-radius: 8px; padding: 1rem; }
    .card-header { font-weight: bold; border-bottom: 1px solid #eee; }
    .card-footer { border-top: 1px solid #eee; margin-top: 0.5rem; }
  </style>
  <div class="card">
    <div class="card-header">
      <slot name="header">Default Header</slot>
    </div>
    <div class="card-body">
      <slot></slot>
    </div>
    <div class="card-footer">
      <slot name="footer">Default Footer</slot>
    </div>
  </div>
</template>

<!-- Using the custom element with slot content -->
<custom-card>
  <span slot="header">My Card Title</span>
  <p>This goes in the default slot (body).</p>
  <p>Multiple elements can go here.</p>
  <button slot="footer">Action Button</button>
</custom-card>

<custom-card>
  <span slot="header">Another Card</span>
  <img src="photo.jpg" alt="Photo" slot="body">
</custom-card>

<script>
  class CustomCard extends HTMLElement {
    constructor() {
      super();
      const template = document.getElementById('card-template');
      const shadow = this.attachShadow({ mode: 'open' });
      shadow.appendChild(template.content.cloneNode(true));
    }
  }
  customElements.define('custom-card', CustomCard);
</script>

<slot> elements in Shadow DOM create insertion points for distributed content. Named slots (slot="name") target specific slots; unnamed slots receive default content. This enables composable web components where consumers provide their own content. attachShadow({ mode: 'open' }) creates the shadow root. Slots enable content projection without coupling the component to specific content.