CSS ::slotted

The ::slotted() pseudo-element is a powerful feature in Shadow DOM that allows you to style elements that are passed into a shadow tree from the outside. This means you can apply styles to elements that are projected into a shadow DOM using the tag. Let's explore how it works with some examples.

Result:

Example 1: Basic Usage of ::slotted()

In this example, we will create a simple web component that uses a to project content, and we will use the ::slotted() pseudo-element to style the slotted content.

<style>
  :host {
    display: block;
    padding: 16px;
    border: 1px solid #ccc;
  }

  ::slotted(p) {
    color: blue;
    font-weight: bold;
  }
</style>

<template>
  <div>
    <slot></slot>
  </div>
</template>

<script>
  class SlotExample extends HTMLElement {
    constructor() {
      super();
      const shadow = this.attachShadow({ mode: 'open' });
      const template = document.querySelector('template').content;
      shadow.appendChild(template.cloneNode(true));
    }
  }

  customElements.define('slot-example', SlotExample);
</script>

<slot-example>
  <p>Hello, this text is slotted!</p>
</slot-example>

In this example, when we place a <p> tag inside the <slot-example> component, it gets styled with blue color and bold font due to the ::slotted(p) CSS rule.

Result:

Hello, this text is slotted!

Example 2: Multiple Slotted Elements

In this example, we will show how to apply styles to multiple slotted elements. We can target any element that gets slotted in the shadow DOM.

<style>
  :host {
    display: block;
    padding: 16px;
    border: 1px solid #ccc;
  }

  ::slotted(h1) {
    color: green;
    text-decoration: underline;
  }

  ::slotted(span) {
    color: red;
    font-size: 1.2em;
  }
</style>

<template>
  <div>
    <slot></slot>
  </div>
</template>

<script>
  class MultipleSlotExample extends HTMLElement {
    constructor() {
      super();
      const shadow = this.attachShadow({ mode: 'open' });
      const template = document.querySelector('template').content;
      shadow.appendChild(template.cloneNode(true));
    }
  }

  customElements.define('multiple-slot-example', MultipleSlotExample);
</script>

<multiple-slot-example>
  <h1>Welcome to Slotted Elements!</h1>
  <span>This is a slotted span element.</span>
</multiple-slot-example>

In this example, the <h1> will be styled with green color and underline, while the <span> will be red and slightly larger font size.

Result:

Welcome to Slotted Elements!

This is a slotted span element.

Summary

The ::slotted() pseudo-element is a great way to style slotted content in web components. By using this pseudo-element, you can easily apply different styles to various types of projected content. Remember that ::slotted() can only style the elements that are directly slotted into the shadow DOM and not the elements within the slotted nodes.