Search code examples
cssweb-componentshadow-dom

Can the CSS :part pseudo-selector be used to style nested web components?


When creating Web Components with encapsulated styles using Shadow DOM, parts of the shadowed markup can be styled using the ::part pseudo selector (https://developer.mozilla.org/en-US/docs/Web/CSS/::part).

Can the part selector be used to target nested shadow parts?

<custom-element>
  #shadow-root
    <div part="thats-easy"></div>
    <another-custom-element part="proxy-part">
      #shadow-root
        <div part="target-me"></div>
    </another-custom-element>
</custom-element>

Current efforts were fruitless:

another-custom-element::part(target-me) { }
custom-element::part(proxy-part) another-custom-element::part(target-me) { }
custom-element::part(proxy-part another-custom-element::part(target-me)) { }
custom-element::part(proxy-part::part(target-me)) { }
```

Solution

  • Fun twist, it is possible and TIL about exportparts
    https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/exportparts

    Example 1

    <style>
      mux-player::part(textspan) { color: red; }
    </style>
    
    <mux-player>
      <template shadowrootmode="open">
        <media-poster-image exportparts="poster, img, innerspan: textspan">
          <template shadowrootmode="open">
            <img part="poster img" src="...">
    
            <span part="innerspan">
              This text will be red because the containing shadow host forwards innerspan to the document as "textspan" and the document style matches it.
            </span>
    
            <span part="textspan">
              This text will not be red because textspan in the document style cannot match against the part inside the inner custom element if it is not forwarded.
            </span>
          </template>
      </template>
    </mux-player>
    

    Example 2

    Example in production with multiple nested custom elements with CSS parts.
    https://github.com/muxinc/elements/blob/main/packages/mux-player/src/template.ts