Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features
Autoplay

    Avoiding CSS Conflicts via Shadow DOM CSS encapsulation

    Yonatan KraYonatan Kra
    htmlHTML 5
    javascriptJavaScript

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss