JGeorgeJ
JGeorgeJ

Reputation: 373

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?

Upvotes: 5

Views: 6139

Answers (1)

connexo
connexo

Reputation: 56754

Only if the component author explicitly 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 {...} (::part cannot be part of a compound selector).

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).

Upvotes: 2

Related Questions