How to target element inside #shadow-root?

303 views Asked by At

I want to change the display style inside of the #shadow-root and am having some trouble targeting it. First question, is it possible to target it through CSS? Or is it better to do it through JS?

#retirement-services-modal #rs-two-col::shadow(.wrapper) {
  display: flex;
  align-items: center;
}
<div id="retirement-services-modal">
  <sdf-layout-two-col id="rs-two-col">
    #shadow-root
    <div class="wrapper">
      <div class="col-1">content goes here</div>
      <div class="col-2">content goes here</div>
    </div>
  </sdf-layout-two-col>
</div>

I am trying to target the .wrapper inside the #shadow-root to add a display: flex; and align-items: center; .

I tried to target it with ::shadow but that did not seem to work. I also tried ::part but that did not seem to work either. Are there any other ways to target it through CSS?

2

There are 2 answers

1
Afzal K. On

it may be more efficient and easier to use JS to target and manipulate the content.

const el = document.querySelector('#rs-two-col'); // access the outer element
const sh = el.shadowRoot; // access the shadow DOM of the element
sh.querySelector('.wrapper').style.cssText = 'display: flex; align-items: center;'; // access the nested element within the shadow DOM and change the CSS property of the element
0
Danny '365CSI' Engelman On

Here is an example using part

<style>
  host-element::part(foo){
    border:10px dashed green;
  }
  div {
    border:20px solid red; /* not applied to shadowDOM */
  }
</style>

<host-element>
  <template shadowrootmode="open">
    <style>
      :host {
        display: inline-block;
        width: 100vw;
        background:hotpink;
      }
      .wrapper {
        text-align:center
      }
    </style>
    <div part="foo" class="wrapper">
      <slot></slot>
    </div>
  </template>
  <h2>LightDOM content slotted in shadowDOM</h2>
</host-element>

Note: Above Declarative shadowDOM notation shadowrootmode is not available in FireFox yet:
https://caniuse.com/declarative-shadow-dom