Reputation: 1313
the following code is a view from chrome dev tools
<textarea>
#shadow-root (user-agent)
<p> This I want to restyle </p>
<textarea>
what CSS selector I have to use if I would like to restyle element in shadow DOM ?
thank you
Upvotes: 4
Views: 6676
Reputation: 10975
ShadowDOM was designed to prevent CSS from leaking INTO or OUT OF the shadowDOM. It is kindof a replacement for <iframe>
which had the same limitations on it. Any CSS in the <iframe>
can not affect the content outside of the <iframe>
and the CSS outside the <iframe>
can not affect the content inside <iframe>
.
But you can affect the inner CSS by using one of the following options:
None of the options below work for existing HTML elements. These examples are only for custom elements you write.
The first way to style an element in shadowDOM is by placing the styles in the shadowDOM with the content.
class MyEl extends HTMLElement {
constructor() {
super();
this.attachShadow({mode:'open'}).innerHTML = `
<style>
p { background-color: #A00; color: white; }
</style>
<p>inner content</p>`;
}
}
customElements.define('my-el', MyEl);
<my-el></my-el>
The second, more limited way, is to use CSS variables:
class MyEl extends HTMLElement {
constructor() {
super();
this.attachShadow({mode:'open'}).innerHTML = `
<style>
p { background-color: var(--bgcolor, #A00); color: var(--color, white); }
</style>
<p>inner content</p>`;
}
}
customElements.define('my-el', MyEl);
body {
--bgcolor: yellow;
--color: navy;
}
<my-el></my-el>
The third way, also limited, is through attributes or properties:
class MyEl extends HTMLElement {
constructor() {
super();
this.attachShadow({mode:'open'}).innerHTML = `
<p>inner content</p>`;
}
set bgColor(val) {
this.shadowRoot.querySelector('p').style.backgroundColor = val;
}
set color(val) {
this.shadowRoot.querySelector('p').style.color = val;
}
}
customElements.define('my-el', MyEl);
const myEl = document.querySelector('my-el');
myEl.bgColor = '#090';
myEl.color = 'white';
<my-el></my-el>
Upvotes: 7