htmlcssshadow-domshadow-root

Overriding CSS of div inside a #shadow-root


We are using a third party plugin and im trying to override the CSS of one div in particular. The problem is that i dont understand how you are suppossed to work with #shadow-root

Image with shadow-root code

I have tried using regular CSS to style to override the .choice--size-small div styling but its not working

div.choice--size-small{
  display:none!important
}

My understanding is that #shadow-root purpose is to isolate everything that is inside so it doesnt get affected by other CSS, so it makes sense.

Can it be done? what is the best way to achieve this? Keep in mind this is a third party software and we can only us CSS and JS to achieve this.


Solution

  • That 3rd party has provided "part" attributes

    But only on the <div part="base"> and <label part="content"> elements

    You can use ::part to style the inside of the shadowRoot, without using JavaScript.

    See: https://developer.mozilla.org/en-US/docs/Web/CSS/::part

    so your (global) CSS can only target that one specific part:

    sc-choice::part(base) {
      display: none;
    }
    

    When an open shadowRoot has no part definitions. You can "get in" with:

    document.querySelector("sc-choice").shadowRoot.append(
      Object.assign(document.createElement("STYLE"),{
                               innerText : `div.choice--size-small {
                                              display:none
                                            }`
      })
    )