Slots Shadow Dom
The shadow DOM specification includes a means for allowing content from outside the shadow root to be rendered inside of our custom element. For those of you who remember AngularJS, this is a similar concept to ng-transclude or using props.children in React. With Web Components, this is done using the element.
Styling a Shadow Dom element from outside has really no effect. You probably noticed, this has no effect.The reason behind is that Shadow Dom have their own little kingdom and cannot be styled. In the shadow DOM, slot name='X' defines an “insertion point”, a place where elements with slot='X' are rendered. Then the browser performs “composition”: it takes elements from the light DOM and renders them in corresponding slots of the shadow DOM. At the end, we have exactly what we want – a component that can be filled with data. See Composition and slots in Eric Bidelman's article on shadow DOM for more information. Style slotted content (distributed children) You can create slots in an element's template that are populated at runtime.
Many types of components, such as tabs, menus, image galleries, and so on, need the content to render.
Just like built-in browser <select>
expects <option>
items, our <custom-tabs>
may expect the actual tab content to be passed. And a <custom-menu>
may expect menu items.
The code that makes use of <custom-menu>
can look like this:
…Then our component should render it properly, as a nice menu with given title and items, handle menu events, etc.
How to implement it?
We could try to analyze the element content and dynamically copy-rearrange DOM nodes. That’s possible, but if we’re moving elements to shadow DOM, then CSS styles from the document do not apply in there, so the visual styling may be lost. Also that requires some coding.
Luckily, we don’t have to. Shadow DOM supports <slot>
elements, that are automatically filled by the content from light DOM.
Named slots
Let’s see how slots work on a simple example.
Here, <user-card>
shadow DOM provides two slots, filled from light DOM:
In the shadow DOM, <slot name='X'>
defines an “insertion point”, a place where elements with slot='X'
are rendered.
Then the browser performs “composition”: it takes elements from the light DOM and renders them in corresponding slots of the shadow DOM. At the end, we have exactly what we want – a component that can be filled with data.
Here’s the DOM structure after the script, not taking composition into account:
We created the shadow DOM, so here it is, under #shadow-root
. Now the element has both light and shadow DOM.
For rendering purposes, for each <slot name='...'>
in shadow DOM, the browser looks for slot='...'
with the same name in the light DOM. These elements are rendered inside the slots:
The result is called “flattened” DOM:
…But the flattened DOM exists only for rendering and event-handling purposes. It’s kind of “virtual”. That’s how things are shown. But the nodes in the document are actually not moved around!
That can be easily checked if we run querySelectorAll
: nodes are still at their places.
So, the flattened DOM is derived from shadow DOM by inserting slots. The browser renders it and uses for style inheritance, event propagation (more about that later). But JavaScript still sees the document “as is”, before flattening.
The slot='...'
attribute is only valid for direct children of the shadow host (in our example, <user-card>
element). For nested elements it’s ignored.
For example, the second <span>
here is ignored (as it’s not a top-level child of <user-card>
):
If there are multiple elements in light DOM with the same slot name, they are appended into the slot, one after another.
For example, this:
Gives this flattened DOM with two elements in <slot name='username'>
:
Slot fallback content
If we put something inside a <slot>
, it becomes the fallback, “default” content. The browser shows it if there’s no corresponding filler in light DOM.
For example, in this piece of shadow DOM, Anonymous
renders if there’s no slot='username'
in light DOM.
Default slot: first unnamed
The first <slot>
in shadow DOM that doesn’t have a name is a “default” slot. It gets all nodes from the light DOM that aren’t slotted elsewhere.
For example, let’s add the default slot to our <user-card>
that shows all unslotted information about the user:
All the unslotted light DOM content gets into the “Other information” fieldset.
Elements are appended to a slot one after another, so both unslotted pieces of information are in the default slot together.
The flattened DOM looks like this:
Menu example
Now let’s back to <custom-menu>
, mentioned at the beginning of the chapter.
We can use slots to distribute elements.
Here’s the markup for <custom-menu>
:
The shadow DOM template with proper slots:
<span slot='title'>
goes into<slot name='title'>
.- There are many
<li slot='item'>
in the template, but only one<slot name='item'>
in the template. So all such<li slot='item'>
are appended to<slot name='item'>
one after another, thus forming the list.
The flattened DOM becomes:
One might notice that, in a valid DOM, <li>
must be a direct child of <ul>
. But that’s flattened DOM, it describes how the component is rendered, such thing happens naturally here.
We just need to add a click
handler to open/close the list, and the <custom-menu>
is ready:
Here’s the full demo:
Of course, we can add more functionality to it: events, methods and so on.
Updating slots
What if the outer code wants to add/remove menu items dynamically?
The browser monitors slots and updates the rendering if slotted elements are added/removed.
Also, as light DOM nodes are not copied, but just rendered in slots, the changes inside them immediately become visible.
So we don’t have to do anything to update rendering. But if the component code wants to know about slot changes, then slotchange
event is available.
For example, here the menu item is inserted dynamically after 1 second, and the title changes after 2 seconds:
The menu rendering updates each time without our intervention.
There are two slotchange
events here:
At initialization:
slotchange: title
triggers immediately, as theslot='title'
from the light DOM gets into the corresponding slot.After 1 second:
slotchange: item
triggers, when a new<li slot='item'>
is added.
Please note: there’s no slotchange
event after 2 seconds, when the content of slot='title'
is modified. That’s because there’s no slot change. We modify the content inside the slotted element, that’s another thing.
If we’d like to track internal modifications of light DOM from JavaScript, that’s also possible using a more generic mechanism: MutationObserver.
Slot API
Finally, let’s mention the slot-related JavaScript methods.
As we’ve seen before, JavaScript looks at the “real” DOM, without flattening. But, if the shadow tree has {mode: 'open'}
, then we can figure out which elements assigned to a slot and, vise-versa, the slot by the element inside it:
node.assignedSlot
– returns the<slot>
element that thenode
is assigned to.slot.assignedNodes({flatten: true/false})
– DOM nodes, assigned to the slot. Theflatten
option isfalse
by default. If explicitly set totrue
, then it looks more deeply into the flattened DOM, returning nested slots in case of nested components and the fallback content if no node assigned.slot.assignedElements({flatten: true/false})
– DOM elements, assigned to the slot (same as above, but only element nodes).
These methods are useful when we need not just show the slotted content, but also track it in JavaScript.
For example, if <custom-menu>
component wants to know, what it shows, then it could track slotchange
and get the items from slot.assignedElements
:
Summary
Usually, if an element has shadow DOM, then its light DOM is not displayed. Slots allow to show elements from light DOM in specified places of shadow DOM.
There are two kinds of slots:
- Named slots:
<slot name='X'>...</slot>
– gets light children withslot='X'
. - Default slot: the first
<slot>
without a name (subsequent unnamed slots are ignored) – gets unslotted light children. - If there are many elements for the same slot – they are appended one after another.
- The content of
<slot>
element is used as a fallback. It’s shown if there are no light children for the slot.
The process of rendering slotted elements inside their slots is called “composition”. The result is called a “flattened DOM”.
Composition does not really move nodes, from JavaScript point of view the DOM is still same.
JavaScript can access slots using methods:
slot.assignedNodes/Elements()
– returns nodes/elements inside theslot
.node.assignedSlot
– the reverse property, returns slot by a node.
If we’d like to know what we’re showing, we can track slot contents using:
slotchange
event – triggers the first time a slot is filled, and on any add/remove/replace operation of the slotted element, but not its children. The slot isevent.target
.- MutationObserver to go deeper into slot content, watch changes inside it.
Now, as we know how to show elements from light DOM in shadow DOM, let’s see how to style them properly. The basic rule is that shadow elements are styled inside, and light elements – outside, but there are notable exceptions.
We’ll see the details in the next chapter.
Style your elements
Polymer supports DOM templating and the shadow DOM API. When you provide a DOM template for your custom element, Polymer then copies in the contents of the template you provided for your element.
Here's an example:
custom-element.js
index.html
The HTML elements in your template become children in your custom element's shadow DOM. Shadow DOM provides a mechanism for encapsulation, meaning that elements inside the shadow DOM don't match selectors outside the shadow DOM.
Likewise, styling rules in side the shadow DOM can't 'leak' out to affect elements outside the shadow DOM.
Shadow DOM permits encapsulation of styling rules for custom elements. You can freely define styling information for your elements, such as fonts, text colors, and classes, without fear of the styles applying outside the scope of your element.
Here's an example:
custom-element.js
index.html
For a detailed explanation of shadow DOM as it applies to Polymer, see Shadow DOM concepts.
For an exploration of the shadow DOM v1 API, see Shadow DOM v1: Self-Contained Web Components.
Use inheritance from document-level styles
When used in an HTML document, your element will still inherit any styling information that applies to its parent element:
custom-element.js
index.html
Styles declared inside shadow DOM will override styles declared outside of it:
custom-element.js
index.html
Style the host element
The element to which shadow DOM is attached is known as the host. To style the host, use the :host
selector.
Inheritable properties of the host element will inherit down the shadow tree, where they apply to the shadow children.
custom-element.js
index.html
Use CSS selectors to style the host element
You can use CSS selectors to determine when and how to style the host. In this code sample:
- The selector
:host
matches any<custom-element>
element - The selector
:host(.blue)
matches<custom-element>
elements of classblue
- The selector
:host(.red)
matches<custom-element>
elements of classred
- The selector
:host(:hover)
matches<custom-element>
elements when they are hovered over
custom-element.js
index.html
Descendant selectors after :host
match elements in the shadow tree. In this example, the CSS selector applies to any p
element in the shadow tree if the host has class 'warning':
custom-element.js
index.html
Styling with the :host
selector is one of two instances where rules inside a shadow tree can affect an element outside a shadow tree. The second instance uses the ::slotted()
syntax to apply styling rules to distributed children. See Composition and slots in Eric Bidelman's article on shadow DOM for more information.
Style slotted content (distributed children)
You can create slots in an element's template that are populated at runtime. For more information on slots, see the documentation on shadow DOM and composition.
The basic syntax for incorporating slotted content looks like this:
custom-element.js
index.html
To style slotted content, use the ::slotted()
syntax.
Note: To work within the Shady CSS scoping shim limitations, and to ensure consistent cross-browser behavior, add a selector to the left of the ::slotted(.classname)
notation (for example, p ::slotted(.classname)
.
::slotted(*)
selects all slotted content:
custom-element.js
index.html
You can select by element type:
custom-element.js
index.html
You can select by class:
custom-element.js
index.html
And you can select by slot name:
custom-element.js
index.html
Style undefined elements
To avoid FOUC (flash of unstyled content), you might want to style custom elements before they aredefined (that is, before the browser has attached their class definition to their markup tag). Ifyou don't, the browser may not apply any styles to the element at first paint. Typically, you'llwant to add styling for a few top-level elements so your application's layout displays while theelement definitions are being loaded.
There is a specification for a :defined
pseudo-class selector to target elements that have beendefined, but the custom elements polyfill doesn't support this selector.
For a polyfill-friendly workaround, add an unresolved
attribute to the element in markup. Forexample:
Then style the unresolved element. For example:
Finally, remove the unresolved
attribute in the element's ready
callback:
Style directional text with the :dir() selector
Slots Without Shadow Dom
The :dir()
CSS selector allows for styling text specific to its orientation(right-to-left or left-to-right). See the documentation on MDN for more information on the :dir()
selector.
The DirMixin
provides limited support for the :dir()
selector. Use of :dir()
requires theapplication to set the dir
attribute on <html>
. All elements will use the same direction.
Individual elements can opt-out of the global direction by setting the dir
attributein HTML or in the ready
callback, but the text direction of these elements must from then on be handledmanually.
Setting dir
on an ancestor (other than html
) has no effect.
For elements that extend PolymerElement
, add DirMixin
to use:dir()
styling.
Here's an example use of the :dir()
selector:
using-dir-selector.js
index.html
Share styles between elements
Use style modules
The preferred way to share styles is with style modules. You can package up styles in a style module, and share them between elements.
The following process is a workaround. While Polymer 3.0 does not use <dom-module>
elements for templating, style modules do. The following process is a workaround for this fact. This process may be updated as required.
To create a style module:
Use JavaScript to create a
<dom-module>
element:Set the
<dom-module>
element'sinnerHTML
property to contain a<template>
element that wraps a<style>
block:Register your style module as an element:
You'll most likely want to package the style module in its own JavaScript file. The element that uses the styles will need to import that file. For example:
When you create the element that will use the styles, include the style module in the opening tag of the style block:
Here's a complete example:
index.html
custom-element.js
style-element.js
Use custom-style in document-level styles
Browsers that implement the current Shadow DOM v1 specifications will automatically encapsulate styles, scoping them to the elements in which they were defined.
Some browsers have not implemented the Shadow DOM v1 specifications. To make sure your apps and elements display correctly in these browsers, you'll need to use custom-style
to ensure that styling information doesn't 'leak' into the local DOM of your elements.
custom-style
enables a set of polyfills that ensure that styles in your apps and elements behave as you would expect from the Shadow DOM v1 specifications, even in browsers that don't implement these specifications.
To ensure that your styles behave according to the Shadow DOM v1 specifications in all browsers, use custom-style
when you define document-level styles:
index.html
custom-style
is not included in the @polymer/polymer/polymer-element.js
module. Import custom-style
from @polymer/polymer/lib/elements/custom-style.js
:
index.html
Don't use custom-style inside an element's template. You should only use custom-style
to define styles for the main document. To define styles for an element's shadow DOM, just use a <style>
block.
Examples
In the following code sample, the document-level style in index.html 'leaks' into the shadow DOM of <custom-element>
in browsers that haven’t implemented the Shadow DOM v1 specs.
Slots Shadow Domain
custom-element.js
index.html
In the following code sample, the developer has used custom-style
to wrap the document-level style block in index.html, preventing the leak.
custom-element.js
index.html