Styling Shadow Parts in CSS

css shadow parts guide
10 November 2024

Introduction to CSS Shadow Parts

CSS Shadow Parts is one of the standout features of CSS that allows you to style the internals of Shadow DOM elements. This feature is especially prevalent in the development of Web Components, a place where we often need to style internal controls and provide internal styling. In general, Shadow DOM allows you to create a separate DOM space for an HTML element. This separate space encapsulates all existing styles on the page and ensures that none of the external styles affect this encapsulated space. However, there are times when we may need access to some of the implementations of Shadow DOM and assign styles to them. With CSS Shadow Parts, we can selectively apply styles to specific elements within the Shadow DOM. To achieve this, we need to use the `` attribute in HTML and then target the relevant parts in CSS. Using Shadow Parts is quite straightforward. First, we define the internal attribute in Shadow DOM using the `part` attribute. Then we can use the `::part` selector in CSS to style these objects. This technique gives us greater power in customizing and managing styles, while still benefiting from the encapsulation provided by the Shadow DOM. This feature is particularly useful for times when we want to create reusable items and apply different styles in various contexts, making it very versatile. In the following practical example, we will observe the use of CSS Shadow Parts:

  <template id="myTemplate">
    <style>
      ::part(button) {
        background-color: blue;
        color: white;
      }
    </style>
    <button part="button">Click Me</button>
  </template>

  <script>
    class MyButton extends HTMLElement {
      constructor() {
        super();
        const template = document.getElementById('myTemplate').content;
        const shadowRoot = this.attachShadow({mode: 'open'});
        shadowRoot.appendChild(template.cloneNode(true));
      }
    }
    customElements.define('my-button', MyButton);
  </script>

  <my-button></my-button>
  

<template id="myTemplate">: Using this tag, we can create a template that will be used in the Shadow DOM.

<style>: Inside this section are styles intended for elements labeled with the part attribute, which we define.

::part(button): This selector specifically targets the element with the part="button" attribute, allowing us to apply styles to it.

class MyButton extends HTMLElement: A new class extending from HTMLElement that allows us to create a custom element.

attachShadow({mode: 'open'}): This line of code creates a new shadow root, which can encapsulate the template content.

FAQ

?

How can I style Shadow DOM?

?

Is CSS Shadow Parts supported in all browsers?

?

Does using Shadow Parts require JavaScript?