Avoiding CSS Conflicts via Shadow DOM CSS encapsulation

Yonatan Kra
InstructorYonatan Kra
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 2 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.

egghead
egghead
~ 4 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today