Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style an element inside a shadow dom

Tags:

css

shadow-dom

I'm applying a custom CSS style on top of an application of which I can't modify the code.

Previously the DOM was like this:

<div class="foo">
  <div class="bar"></div>
</div>

and I was modifying it easily with .foo .bar.

But they released a new version of the app and now the child is in a shadow DOM:

<div class="foo">
  #shadow-root
    <div class="bar"></div>
</div>

and obviously my previous selector does not work anymore. How can I reach this .bar, only if it is inside a .foo? I read about ::part(), but I can't add part="bar" on the DOM element. Thank you for your help.

like image 361
Fla Avatar asked Oct 23 '25 15:10

Fla


1 Answers

Currently with only CSS, if part is not used, there is no way to target the child elements from the outside. This is intended and the motivation for this is to allow the Shadow DOM creator to fully control what are exposed to be styled outside.

However, if JavaScript is allowed and the Shadow DOM is created with mode open, you can target the child element using shadowRoot.querySelector.

const host = document.querySelector("#host");
const shadow = host.attachShadow({ mode: "open" });
const div = document.createElement("div");
div.className = "bar";
div.textContent = "I'm in the shadow DOM";
shadow.appendChild(div);


document.querySelector("#host").shadowRoot.querySelector(".bar").style.color = "red";
<div id="host" class="foo"></div>

You can also inject styles that includes rules that targets the bar using JavaScript, but again only when the mode is open.

Otherwise, you'll have to check if the app is using custom properties on the styles you need to customize or style the Shadow DOM using inherited properties.

like image 53
SyndRain Avatar answered Oct 26 '25 05:10

SyndRain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!