3

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

4
  • Which browser are you using? Commented Jun 20, 2021 at 3:46
  • What are those some css? Can you please specify the issue? Commented Jun 20, 2021 at 4:09
  • @deepakchethan i'm using google-chrome Commented Jun 20, 2021 at 4:22
  • @yurzui, yeah, the global styles under style.css affects the elements under AppComponent even though it has ViewEncapsulation.ShadowDom. I've always thought that global styles won't affect elements under ShadowDom. Commented Jun 20, 2021 at 4:23

1 Answer 1

5

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:

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

3 Comments

I always put the lamplightdev.com/blog/2019/03/26/… blog first, it is the best written explanation
Awesome! Now, it all makes sense. Thanks a lot. Is there any way to automatically add :host { all: initial } on creating of a component?
You can create your own schematic for component where you can have this css

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.