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

How to Override Styles in a Shadow-Root Element?

Susan Sarandon
Release: 2024-11-12 22:41:02
Original
344 people have browsed it

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; }';
Copy after login

Next, append the style element to the shadow root:

host.shadowRoot.appendChild(style);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template