'Select element in shadow-root with css only

is there any way how can I change CSS inside shadow-root without using JS I mean CSS only. I looked through some things but cant find a way how to do it without js.

lets say we have code

<div id="parent">
   #shadow-root (open)
     <div id="child">
     </div>
</div>

how can I access child with CSS only?



Solution 1:[1]

Only if the component author explicit allows it using the part attribute on the element in the shadow DOM. In that case you can apply CSS to that element using the ::part pseudo element selector:

Here's an example:

customElements.define('foo-bar', class extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({mode: 'open'})
    this.shadowRoot.innerHTML = '<p part="baz">foo-bar here</p>';
  }
});
::part(baz) {
  background-color: red;
}
<foo-bar></foo-bar>

Please note that you can not do something like ::part(foo) + .internal-css-class {...}.

Other than that, you can always work with CSS's inherited properties, these also affect the shadow DOM. E.g. putting the web component into an <h1> will affect it's font-size and -weight (unless it specifically defines its own values for those properties).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1