Shadow DOM v1: Self-Contained Web Components

TL;DR

Shadow DOM removes the brittleness of building web apps. The brittleness
comes from the global nature of HTML, CSS, and JS. Over the years we've
invented an exorbitant numberoftools
to circumvent the issues. For example, when you use a new HTML id/class,
there's no telling if it will conflict with an existing name used by the page.
Subtle bugs creep up,
CSS specificity becomes a huge issue (!important all the things!), style
selectors grow out of control, and
performance can suffer. The list
goes on.

Shadow DOM fixes CSS and DOM. It introduces scoped styles to the web
platform. Without tools or naming conventions, you can bundle CSS with
markup, hide implementation details, and author self-contained
components in vanilla JavaScript.

Introduction

Note:Already familiar with Shadow DOM? This article describes the new
Shadow DOM v1 spec. If you've been using Shadow DOM, chances are you're
familiar with the
v0 version that shipped in Chrome 35, and the webcomponents.js polyfills.
The concepts are the same, but the v1 spec has important API differences. It's
also the version that all major browsers have agreed to implement, with
implementations already in Safari, Chrome and Firefox. Keep reading
to see what's new or check out the section on
History and browser support for more info.

You don't have to author web components that use shadow DOM. But when you do,
you take advantage of its benefits (CSS scoping, DOM encapsulation,
composition) and build reusable
custom elements,
which are resilient, highly configurable, and extremely reusable. If custom
elements are the way to create a new HTML (with a JS API), shadow DOM is the
way you provide its HTML and CSS. The two APIs combine to make a component
with self-contained HTML, CSS, and JavaScript.

Shadow DOM is designed as a tool for building component-based apps. Therefore,
it brings solutions for common problems in web development:

Simplifies CSS - Scoped DOM means you can use simple CSS selectors, more
generic id/class names, and not worry about naming conflicts.

Productivity - Think of apps in chunks of DOM rather than one large
(global) page.

Note: Although you can use the shadow DOM API and its benefits outside of web
components, I'm only going to focus on examples that build on custom elements.
I'll be using the custom elements v1 API in all examples.

fancy-tabs demo

Throughout this article, I'll be referring to a demo component (<fancy-tabs>)
and referencing code snippets from it. If your browser supports the APIs, you
should see a live demo of it just below. Otherwise, check out the
full source on Github.

What is shadow DOM?

Background on DOM

HTML powers the web because it's easy to work with. By declaring a few tags, you
can author a page in seconds that has both presentation and structure. However,
by itself HTML isn't all that useful. It's easy for humans to understand a text-
based language, but machines need something more. Enter the Document Object
Model, or DOM.

When the browser loads a web page it does a bunch of interesting stuff. One of
the things it does is transform the author's HTML into a live document.
Basically, to understand the page's structure, the browser parses HTML (static
strings of text) into a data model (objects/nodes). The browser preserves the
HTML's hierarchy by creating a tree of these nodes: the DOM. The cool thing
about DOM is that it's a live representation of your page. Unlike the static
HTML we author, the browser-produced nodes contain properties, methods, and best
of all...can be manipulated by programs! That's why we're able to create DOM
elements directly using JavaScript:

DOM...in the shadows

Shadow DOM is just normal DOM with two differences: 1) how it's created/used and
2) how it behaves in relation to the rest of the page. Normally, you create DOM
nodes and append them as children of another element. With shadow DOM, you
create a scoped DOM tree that's attached to the element, but separate from its
actual children. This scoped subtree is called a shadow tree. The element
it's attached to is its shadow host. Anything you add in the shadows becomes
local to the hosting element, including <style>. This is how shadow DOM
achieves CSS style scoping.

Creating shadow DOM

A shadow root is a document fragment that gets attached to a “host” element.
The act of attaching a shadow root is how the element gains its shadow DOM. To
create shadow DOM for an element, call element.attachShadow():

There are a couple of interesting things going on here. The first is that the
custom element creates its own shadow DOM when an instance of <fancy-tabs>
is created. That's done in the constructor(). Secondly, because we're creating
a shadow root, the CSS rules inside the <style> will be scoped to <fancy-tabs>.

Note: When you try to run this example, you'll probably notice that nothing
renders. The user's markup seemingly disappears! That's because the element's
shadow DOM is rendered in place of its children. If you want to display the
children, you need to tell the browser where to render them by placing a
<slot> element in your shadow DOM. More on that
later.

Composition and slots

Composition is one of the least understood features of shadow DOM, but it's
arguably the most important.

In our world of web development, composition is how we construct apps,
declaratively out of HTML. Different building blocks (<div>s, <header>s,
<form>s, <input>s) come together to form apps. Some of these tags even work
with each other. Composition is why native elements like <select>,
<details>, <form>, and <video> are so flexible. Each of those tags accepts
certain HTML as children and does something special with them. For example,
<select> knows how to render <option> and <optgroup> into dropdown and
multi-select widgets. The <details> element renders <summary> as a
expandable arrow. Even <video> knows how to deal with certain children:
<source> elements don't get rendered, but they do affect the video's behavior.
What magic!

Terminology: light DOM vs. shadow DOM

Shadow DOM composition introduces a bunch of new fundamentals in web
development. Before getting into the weeds, let's standardize on some
terminology so we're speaking the same lingo.

Light DOM

The markup a user of your component writes. This DOM lives outside the
component's shadow DOM. It is the element's actual children.

The DOM a component author writes. Shadow DOM is local to the component and
defines its internal structure, scoped CSS, and encapsulates your implementation
details. It can also define how to render markup that's authored by the consumer
of your component.

The result of the browser distributing the user's light DOM into your shadow
DOM, rendering the final product. The flattened tree is what you ultimately see
in the DevTools and what's rendered on the page.

The <slot> element

Shadow DOM composes different DOM trees together using the <slot> element.
Slots are placeholders inside your component that users can fill with their
own markup. By defining one or more slots, you invite outside markup to render
in your component's shadow DOM. Essentially, you're saying "Render the user's
markup over here".

Note: Slots are a way of creating a "declarative API" for a web component. They
mix-in the user's DOM to help render the overall component, thus, composing
different DOM trees together.

Elements are allowed to "cross" the shadow DOM boundary when a <slot> invites
them in. These elements are called distributed nodes. Conceptually,
distributed nodes can seem a bit bizarre. Slots don't physically move DOM; they
render it at another location inside the shadow DOM.

A component can define zero or more slots in its shadow DOM. Slots can be empty
or provide fallback content. If the user doesn't provide light DOM
content, the slot renders its fallback content.

Notice our component is able to handle different configurations, but the
flattened DOM tree remains the same. We can also switch from <button> to
<h2>. This component was authored to handle different types of children...just
like <select> does!

Styling

There are many options for styling web components. A component that uses shadow
DOM can be styled by the main page, define its own styles, or provide hooks (in
the form of CSS custom properties) for users to override defaults.

CSS selectors used inside shadow DOM apply locally to your component. In
practice, this means we can use common id/class names again, without worrying
about conflicts elsewhere on the page. Simpler CSS selectors are a best practice
inside Shadow DOM. They're also good for performance.

One gotcha with :host is that rules in the parent page have higher specificity
than :host rules defined in the element. That is, outside styles win. This
allows users to override your top-level styling from the outside. Also, :host
only works in the context of a shadow root, so you can't use it outside of
shadow DOM.

The functional form of :host(<selector>) allows you to target the host if it
matches a <selector>. This is a great way for your component to encapsulate
behaviors that react to user interaction or state or style internal nodes based
on the host.

Styling based on context

:host-context(<selector>) matches the component if it or any of its ancestors
matches <selector>. A common use for this is theming based on a component's
surroundings. For example, many people do theming by applying a class to
<html> or <body>:

<body class="darktheme">
<fancy-tabs>
...
</fancy-tabs>
</body>

:host-context(.darktheme) would style <fancy-tabs> when it's a descendant
of .darktheme:

If you remember from before, <slot>s do not move the user's light DOM. When
nodes are distributed into a <slot>, the <slot> renders their DOM but the
nodes physically stay put. Styles that applied before distribution continue to
apply after distribution. However, when the light DOM is distributed, it can
take on additional styles (ones defined by the shadow DOM).

In this example, there are two slots: a named slot for the tab titles, and a
slot for the tab panel content. When the user selects a tab, we bold their selection
and reveal its panel. That's done by selecting distributed nodes that have the
selected attribute. The custom element's JS (not shown here) adds that
attribute at the correct time.

Styling a component from the outside

There are a couple of ways to style a component from the outside. The easiest
way is to use the tag name as a selector:

Styling the component itself will only get you so far. But what happens if you
want to style the internals of a component? For that, we need CSS custom
properties.

Creating style hooks using CSS custom properties

Users can tweak internal styles if the component's author provides styling hooks
using CSS custom properties. Conceptually, the idea is similar to
<slot>. You create "style placeholders" for users to override.

In this case, the component will use black as the background value since the
user provided it. Otherwise, it would default to #9E9E9E.

Note: As the component author, you're responsible for letting developers know
about CSS custom properties they can use. Consider it part of your component's
public interface. Make sure to document styling hooks!

Advanced topics

Creating closed shadow roots (should avoid)

There's another flavor of shadow DOM called "closed" mode. When you create a
closed shadow tree, outside JavaScript won't be able to access the internal DOM
of your component. This is similar to how native elements like <video> work.
JavaScript cannot access the shadow DOM of <video> because the browser
implements it using a closed-mode shadow root.

Note: Closed shadow roots are not very useful. Some developers will see closed
mode as an artificial security feature. But let's be clear, it's not a
security feature. Closed mode simply prevents outside JS from drilling into an
element's internal DOM.

Here's my summary of why you should never create web components with
{mode: 'closed'}:

Closed mode prevents your custom element code from accessing its own
shadow DOM. That's complete fail. Instead, you'll have to stash a reference
for later if you want to use things like querySelector(). This completely
defeats the original purpose of closed mode!

Closed mode makes your component less flexible for end users. As you
build web components, there will come a time when you forget to add a
feature. A configuration option. A use case the user wants. A common
example is forgetting to include adequate styling hooks for internal nodes.
With closed mode, there's no way for users to override defaults and tweak
styles. Being able to access the component's internals is super helpful.
Ultimately, users will fork your component, find another, or create their
own if it doesn't do what they want :(

Working with slots in JS

The shadow DOM API provides utilities for working with slots and distributed
nodes. These come in handy when authoring a custom element.

slotchange event

The slotchange event fires when a slot's distributed nodes changes. For
example, if the user adds/removes children from the light DOM.

Note:slotchange does not fire when an instance of the component is
first initialized.

To monitor other types of changes to light DOM, you can setup a
MutationObserver
in your element's constructor.

What elements are being rendering in a slot?

Sometimes it's useful to know what elements are associated with a slot. Call
slot.assignedNodes() to find which elements the slot is rendering. The
{flatten: true} option will also return a slot's fallback content (if no nodes
are being distributed).

As an example, let's say your shadow DOM looks like this:

<slot><b>fallback content</b></slot>

Usage

Call

Result

<my-component>component text</my-component>

slot.assignedNodes();

[component text]

<my-component></my-component>

slot.assignedNodes();

[]

<my-component></my-component>

slot.assignedNodes({flatten: true});

[<b>fallback content</b>]

What slot is an element assigned to?

Answering the reverse question is also possible. element.assignedSlot tells
you which of the component slots your element is assigned to.

The Shadow DOM event model

When an event bubbles up from shadow DOM it's target is adjusted to maintain the
encapsulation that shadow DOM provides. That is, events are re-targeted to look
like they've come from the component rather than internal elements within your
shadow DOM. Some events do not even propagate out of shadow DOM.

Handling focus

If you recall from shadow DOM's event model, events that are fired
inside shadow DOM are adjusted to look like they come from the hosting element.
For example, let's say you click an <input> inside a shadow root:

The focus event will look like it came from <x-focus>, not the <input>.
Similarly, document.activeElement will be <x-focus>. If the shadow root
was created with mode:'open' (see closed mode), you'll also be
able access the internal node that gained focus:

document.activeElement.shadowRoot.activeElement // only works with open mode.

If there are multiple levels of shadow DOM at play (say a custom element within
another custom element), you need to recursively drill into the shadow roots to
find the activeElement:

Above is the result when <x-focus> is focused (user click, tabbed into,
focus(), etc.), "Clickable Shadow DOM text" is clicked, or the internal
<input> is focused (including autofocus).

If you were to set delegatesFocus: false, here's what you would see instead:

delegatesFocus: false and the internal <input> is focused.
delegatesFocus: false and <x-focus>
gains focus (e.g. it has tabindex="0").
delegatesFocus: false and "Clickable Shadow DOM text" is
clicked (or other empty area within the element's shadow DOM is clicked).

Tips & Tricks

Over the years I've learned a thing or two about authoring web components. I
think you'll find some of these tips useful for authoring components and
debugging shadow DOM.

Use CSS containment

Typically, a web component's layout/style/paint is fairly self-contained. Use
CSS containment in :host for a perf
win:

Resetting inheritable styles

Inheritable styles (background, color, font, line-height, etc.) continue
to inherit in shadow DOM. That is, they pierce the shadow DOM boundary by
default. If you want to start with a fresh slate, use all: initial; to reset
inheritable styles to their initial value when they cross the shadow boundary.

History & browser support

If you've been following web components for the last couple of years, you'll
know that Chrome 35+/Opera have been shipping an older version of shadow DOM for
some time. Blink will continue to support both versions in parallel for some
time. The v0 spec provided a different method to create a shadow root
(element.createShadowRoot instead of v1's element.attachShadow). Calling the
older method continues to create a shadow root with v0 semantics, so existing v0
code won't break.

Conclusion

For the first time ever, we have an API primitive that does proper CSS scoping,
DOM scoping, and has true composition. Combined with other web component APIs
like custom elements, shadow DOM provides a way to author truly encapsulated
components without hacks or using older baggage like <iframe>s.

Don't get me wrong. Shadow DOM is certainly a complex beast! But it's a beast
worth learning. Spend some time with it. Learn it and ask questions!

FAQ

Shadow DOM is not a security feature. It's a lightweight tool for scoping CSS
and hiding away DOM trees in component. If you want a true security boundary,
use an <iframe>.

Does a web component have to use shadow DOM?

Nope! You don't have to create web components that use shadow DOM. However,
authoring custom elements that use Shadow DOM means you can take
advantage of features like CSS scoping, DOM encapsulation, and composition.