Home  >  Article  >  Web Front-end  >  How to Override Styles in a Shadow-Root Element?

How to Override Styles in a Shadow-Root Element?

Susan Sarandon
Susan SarandonOriginal
2024-11-12 22:41:02299browse

How to Override Styles in a Shadow-Root Element?

Overriding Styles in a Shadow-Root Element

Shadow DOM isolates styles within its scope, making it challenging to modify them using global CSS rules. To address this, consider the following workaround:

Inject Style Directly into Shadow Root:

Create a new style element and set its innerHTML to the desired style changes:

var style = document.createElement('style');
style.innerHTML = '.the-class-name { property-name: my-value; }';

Next, append the style element to the shadow root:

host.shadowRoot.appendChild(style);

Note: This approach requires the Shadow DOM to be set to 'open' mode.

Chrome 73 and Opera 60 Enhancement:

In recent versions of these browsers, a CSSStyleSheet object can be instantiated and applied directly to a Shadow DOM:

var sheet = new CSSStyleSheet;
sheet.replaceSync(`.color { color: pink }`);
host.shadowRoot.adoptedStyleSheets.push(sheet);

Caution: Do not add the same style sheet multiple times to the adoptedStyleSheets array, especially during SPA page reloads.

The above is the detailed content of How to Override Styles in a Shadow-Root Element?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn