Avoiding CSS Conflicts via Shadow DOM CSS encapsulation

Yonatan Kra
InstructorYonatan Kra
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 3 years ago

Shadow DOM is part of the web components specification. It allows us to ship self contained components along with their style and isolate the component from global style while "protecting" the host application from styles defined inside the component. In this lesson you will learn how to setup a shadow DOM and see the CSS encapsulation in action.

Instructor: [00:01] Shadow DOM is used inside custom elements, so we will define one now. We'll start by adding a template with a div, add the class text to the div, and inside, add a slot named content. Let's add our script now, with a reference to the template.

[00:24] The final custom element, we'll call it custom element. Inside its constructor, we use the elements attachShadow method, with mode open as a parameter in order to instantiate the shadow root.

[00:40] This shadow root can be used now as an HTML element. We just append the template's content clone inside, we define the element, we use the element in the DOM, we add a slotted paragraph. We refresh, and we see the element is rendered. In order to see the Shadow DOM style encapsulation, let's add style to our template, and see the change.

[01:09] Now, let's add a simple div with the same class. We'll refresh, and we see that it's loaded with no styling. Most apps have global style, so let's add that now. Just copy the template style. To make things interesting, let's make the global style more specific.

[01:37] Let's change things to add color, underline, and bigger font, refresh, and we see that the div outside the shadow has the global style.