Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Avoiding CSS Conflicts via Shadow DOM CSS encapsulation

    Yonatan KraYonatan Kra
    htmlHTML 5

    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.



    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




    Instructor: 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.

    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.

    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.

    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.

    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.