8

I am trying to add CSS to element inside shadow-root by adding class to it. I have angular component where I have. CSS

.test {
    border: 1px solid red;
}

TS

document.getElementById('my-div').shadowRoot.querySelector('.some-wrapper').classList.add('test')

The thing is that i can see that class is added but that class seems to be empty like it adds no CSS to element only class. What I am doing wrong?

1 Answer 1

8

To make your styles work in a Shadow DOM, you should use :host([selector]):

:host(.test ) {
    border: 1px solid red;
}

The :host selector allows to select the shadow host (the element containing the shadow tree). As a general rule, local styles work only inside the shadow tree, and document styles work outside of it. But there are few exceptions. A shadow host is a DOM node that contains a shadow root. It is a regular element node within the parent page that hosts the scoped shadow subtree. Any child nodes that reside under the shadow host are still selectable, with the exception of the shadow root.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you even for your explanation. Do you know about any exception where this cant work? I am trying to implement it but all I see is that element have class test but css from it even when i add :host(.test)...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.