6

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)) { }
```
Philipp Gfeller
  • 1,167
  • 2
  • 15
  • 36

2 Answers2

4

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

luwes
  • 854
  • 11
  • 19
  • [Further reading about using `exportparts`](https://web.archive.org/web/20220908033421/https://github.com/fergald/docs/blob/master/explainers/css-shadow-parts-1.md) – OfirD Oct 12 '22 at 16:04
  • Future readers: My [question](https://stackoverflow.com/questions/74044803/how-to-position-nested-shadow-doms-on-top-of-each-other) here demonstrates how `exportparts` is used with nested components. – OfirD Oct 12 '22 at 16:08
3

Nope. It is not possible. It kind a breaks the encapsulation principle. The right way is to use proper theming. That means using a combination of:

::part - For direct theming of the component
:host-context - for theming based on the context
::slotted - For styling the slotted element inside the styling

For more dynamic theming, you can use above styles in combination with Element.matches API. Whatever the class/context that the user of the component has set, you can then change the styling of nested children component.

On a side note, modifying the styling of a decadent component (children of children) is a bad practice even when not using Shadow DOM or Web Components. It will result in a brittle non-maintainable CSS.

Edit Note:

:host-context is not implemented in all browsers and probably never will.

Harshal Patil
  • 17,838
  • 14
  • 60
  • 126