Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ViewEncapsulation.ShadowDOM doesn't isolate css styles

I've read that ShadowDOM isolates the shadow dom tree from external css so i've tried to play around with it in Angular using ViewEncapsulation.ShadowDom, but it seems like the global css are still leaking into the Shadow DOM.

Kindly see the code here: https://stackblitz.com/edit/shadow-dom-test?file=src/app/app.component.ts

import { Component, VERSION, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  encapsulation: ViewEncapsulation.ShadowDom
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;
}

After that, setting any css in style.css will affect the elements under AppComponent even though the encapsulation is set to ViewEncapsulation.ShadowDomand the component is contained under ShadowDom tree.

See the screenshot below, Font-size is inherited by elements under ShadowDOM

enter image description here

like image 636
The.Wolfgang.Grimmer Avatar asked Aug 24 '26 12:08

The.Wolfgang.Grimmer


1 Answers

From w3 spec

3.3.2 Inheritance

The top-level elements of a shadow tree inherit from their host element

What this means is that inheritable styles, like color or font-size among others, continue to inherit in shadow DOM, will pierce the shadow DOM and affect your component's styling.

You can force it back to initial state by using

app.component.ts

:host {
  all: initial;
}

It will prevent inheritance without affecting other CSS defined within the ShadowDOM.

Forked Stackblitz

See also:

  • https://polymer-library.polymer-project.org/2.0/docs/devguide/style-shadow-dom#use-inheritance-from-document-level-styles
  • https://css-tricks.com/playing-shadow-dom/
  • https://lamplightdev.com/blog/2019/03/26/why-is-my-web-component-inheriting-styles/
like image 98
yurzui Avatar answered Aug 27 '26 05:08

yurzui



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!