DEV Community

jmckenney
jmckenney

Posted on

Web Component Style Encapsulation In 5 Minutes

The Problem

Since the dawn of the data webs (well, shortly after the dawn), every ui element was governed solely and entirely by one overarching style cascade. What happens when you want to carefully protect an area of your UI from css overrides?

The Solution

Shadow DOM. Shadow DOM touches on many topics under the umbrella of web components and also provides JS encapsulation. Today we are going to hone in on a few key aspects of style encapsulation.

Custom elements by themselves provide only a minimal amount of change from the historic methods of styling. In the following example you will see that because a custom element is unique in name, a style author can utilize the custom element quote/unquote namespace to provide a healthy amount of specificity to custom styling thereby offering a minimal amount of protection from css overrides.

As you can see, the p styling was overrideen by the parent-element p styling. Please take note that lit-element enables Shadow DOM by default and the example above disabled that via the createRenderRoot() override. This enabled us to utilize lit-element while still showing a Custom Element without Shadow DOM enabled.

The Big Reveal

Now we get our example of style encapsulation.

A few questions may come to mind after looking at this example:

  • Why does it say Hello World rather than the template's string of Style me carefully?

The answer is due to the magic of slots. Notice how the browser treats this area somewhat like a symlink in linux file systems. Though the node lives inside the shadow root, the content and styles reference the link back in the light DOM.

  • Why are we able to style the slotted content from outside, but we are unable to style the content existing inside the Shadow DOM that doesn't reference slotted content?

Shadow DOM protects, slots allow for styling. This is starting to get fun.

It's like a symlink

The Styling API

Now we have this clean and beautiful specification that allows us to continue composing html elements together while simultaneously encapsulating styles. I have to hand it to the specification creators for browsers. This had to have taken a lot of forethought and creativity.

In the event that the author of the encapsulated area wants to allow branding and some styling to be brought in from the outside, the spec has options for this as demonstrated below.

In the next article I'll discuss how web components also provide a way to encapsulate JavaScript. Keep a look out for a video walkthrough of this article.

Credit Where Credit Is Due

https://gist.github.com/praveenpuglia/0832da687ed5a5d7a0907046c9ef1813

Top comments (1)

Collapse
 
jmckenney profile image
jmckenney

A huge shoutout to open-wc.org/ who has also provided a lot of groundwork for lit-element based understanding and examples.