1. Introduction
Shadow DOM allows authors to separate their page into "components", subtrees of markup whose details are only relevant to the component itself, not the outside page. This reduces the chance of a style meant for one part of the page accidentally over-applying and making a different part of the page look wrong. However, this styling barrier also makes it harder for a page to interact with its components when it actually wants to do so.
This specification defines the ::part() pseudo-element, which allows an author to style specific, purposely exposed elements in a shadow tree from the outside page’s context. In combination with custom properties, which let the outside page pass particular values (such as theme colors) into the component for it to do with as it will, these pseudo-elements allow components and the outside page to interact in safe, powerful ways, maintaining encapsulation without surrendering all control.
The :host pseudo-class and its functional counterpart :host() match the shadow tree’s shadow host.
Furthermore, the ::slotted pseudo-element and the related :has-slotted pseudo-class provide ways to interact with slots and their assigned shadow tree.
Tests
General tests for shadow parts
- all-hosts.html (live test) (source)
- animation-part.html (live test) (source)
- chaining-invalid-selector.html (live test) (source)
- complex-matching.html (live test) (source)
- complex-non-matching.html (live test) (source)
- different-host.html (live test) (source)
- double-forward.html (live test) (source)
- grouping-with-checked.html (live test) (source)
- grouping-with-disabled.html (live test) (source)
- host-stylesheet.html (live test) (source)
- inner-host.html (live test) (source)
- interaction-with-nested-pseudo-class.html (live test) (source)
- interaction-with-placeholder.html (live test) (source)
- interaction-with-pseudo-elements.html (live test) (source)
- invalidation-complex-selector-forward.html (live test) (source)
- invalidation-complex-selector.html (live test) (source)
- invalidation-part-pseudo.html (live test) (source)
- multiple-parts.html (live test) (source)
- part-after-combinator-invalidation.html (live test) (source)
- part-mutation-pseudo.html (live test) (source)
- part-nested-pseudo.html (live test) (source)
- precedence-part-vs-part.html (live test) (source)
- pseudo-classes-after-part.html (live test) (source)
- pseudo-elements-after-part.html (live test) (source)
- serialization.html (live test) (source)
- simple-forward-shorthand.html (live test) (source)
- simple-forward.html (live test) (source)
- simple-important.html (live test) (source)
- simple-important-important.html (live test) (source)
- simple-important-inline.html (live test) (source)
- simple.html (live test) (source)
- simple-important.html (live test) (source)
- simple-inline.html (live test) (source)
- style-sharing.html (live test) (source)
2. Default Styles for Custom Elements
This section is experimental, and is under active discussion. Do not implement without consulting the CSSWG.
When defining custom elements, one often wants to set up "default" styles for them, akin to the user-agent styles that apply to built-in elements. This is, unfortunately, hard to do in vanilla CSS, due to issues of scoping and specificity—the element in question might be used in shadow trees, and thus is unreachable by any selector targeting it in the outermost document; and selectors, even low-specificity ones like simple type selectors, can accidentally override author-level styles meant to target the element.
To aid in this, this section defines a way to create a stylesheet of "default element styles" for a given element. This stylesheet applies across the entire document, in all shadow trees, and the rules in it apply at the user-agent origin, so author-level rules automatically win.
Windows gain a private slot [[defaultElementStylesMap]]
which is a map of local names to stylesheets.
These stylesheets must apply to every document in the window. They must be interpreted as user agent stylesheets.
Note: This implies, in particular, that they apply to all shadow trees in every document, and that the declarations in them are from the user-agent origin.
For the purpose of the cascade, these stylesheets are ordered after the user agent’s own stylesheets; their relative ordering doesn’t matter as it is not observable.
Within these stylesheets, complex selectors must be treated as invalid. Every compound selector must be treated as containing an additional type selector that selects elements with the local name that the stylesheet is keyed with.
Do we need to restrict the at-rules that can be used in these sheets? For example, do we allow an @font-face? I’m going to leave it as allowed unless/until I hear complaints.
This specification does not define how to add to, remove from, or generally manipulate
the [[defaultElementStylesMap]].
It is expected that other specifications,
such as [DOM],
will define ways to do so.
3. Shadow Encapsulation
3.1. Informative Explanation of Shadow DOM
The following is a non-normative explanation of several concepts normatively defined in the DOM Standard [DOM], to aid in understanding what this spec defines without having to fully grok the DOM Standard.
In addition to the qualities of an element tree defined in Selectors Level 4 § data-model, the DOM Standard adds several new concepts related to shadow trees, several of which are relevant to CSS.
An element can host a shadow tree, which is a special kind of document fragment with a shadow root (a non-element node) at its root. Children of the shadow root are ordinary elements and other nodes. The element hosting the shadow tree is its host, or shadow host.
The elements in a shadow tree are not descendants of the shadow host in general (including for the purposes of Selectors like the descendant combinator). However, the shadow tree, when it exists, is used in the construction of the flattened element tree, which CSS uses for all purposes after Selectors (including inheritance and box construction).
Loosely, the shadow tree is treated as the shadow host’s contents
instead of its normal light tree contents.
However, some of its light tree children
can be "pulled into" the shadow tree
by assigning them to slots.
This causes them to be treated as children of the slot
for CSS purposes.
The slots can then be assigned to slots
in deeper shadow trees;
luckily, slots themselves don’t generate boxes by default,
so you don’t get an unpredictable cascade of slot wrapper elements
disrupting your CSS.
If nothing is explicitly assigned to a slot, the slot’s own children are instead assigned to it, as a sort of "default" contents.
3.2. Shadow DOM and Selectors
3.2.1. Matching Selectors Against Shadow Trees
When a selector is matched against a shadow tree, the selector match list is initially the shadow host, followed by all children of the shadow tree’s shadow root and their descendants, ordered by a pre-order traversal.
Rewrite this against the newer call forms of the matching algorithms.
Note: Remember that the descendants of an element are based on the light tree children of the element, which does not include the shadow trees of the element.
When a selector is matched against a tree, its tree context is the root of the root elements passed to the algorithm. If the tree context is a shadow root, that selector is being matched in the context of a shadow tree.
querySelector() when called from a shadow root.
Declarations inherit the tree context of the selector that was matched to apply them.
Tests
- css-scoping-shadow-assigned-node-with-before-after.html (live test) (source)
- css-scoping-shadow-dynamic-remove-style-detached.html (live test) (source)
- css-scoping-shadow-assigned-node-with-rules.html (live test) (source)
- css-scoping-shadow-host-with-before-after.html (live test) (source)
- css-scoping-shadow-invisible-slot.html (live test) (source)
- css-scoping-shadow-root-hides-children.html (live test) (source)
- css-scoping-shadow-slot-display-override.html (live test) (source)
- css-scoping-shadow-slot-fallback.html (live test) (source)
- css-scoping-shadow-slot.html (live test) (source)
- css-scoping-shadow-slot-style.html (live test) (source)
- css-scoping-shadow-with-outside-rules.html (live test) (source)
- css-scoping-shadow-with-rules.html (live test) (source)
- css-scoping-shadow-with-rules-no-style-leak.html (live test) (source)
- keyframes-001.html (live test) (source)
- keyframes-002.html (live test) (source)
- shadow-assign-dynamic-001.html (live test) (source)
- shadow-disabled-sheet-001.html (live test) (source)
- shadow-fallback-dynamic-001.html (live test) (source)
- shadow-fallback-dynamic-002.html (live test) (source)
- shadow-fallback-dynamic-003.html (live test) (source)
- shadow-fallback-dynamic-004.html (live test) (source)
- shadow-fallback-dynamic-005.html (live test) (source)
- shadow-host-with-before-after.html (live test) (source)
- shadow-link-rel-stylesheet-no-style-leak.html (live test) (source)
- shadow-multiple-links.html (live test) (source)
- shadow-reassign-dynamic-001.html (live test) (source)
- shadow-reassign-dynamic-002.html (live test) (source)
- shadow-reassign-dynamic-004.html (live test) (source)
- shadow-reassign-dynamic-005-crash.html (live test) (source)
- shadow-reassign-dynamic-006.html (live test) (source)
- shadow-root-insert-into-document.html (live test) (source)
- slotted-text-with-flex.html (visual test) (source)
- whitespace-crash-001.html (live test) (source)
3.2.2. Selecting Shadow Hosts from within a Shadow Tree
A shadow host is outside of the shadow tree it hosts, and so would ordinarily be untargettable by any selectors evaluated in the context of the shadow tree (as selectors are limited to a single tree), but it is sometimes useful to be able to style it from inside the shadow tree context.
For the purpose of Selectors, a shadow host also appears in its shadow tree, with the contents of the shadow tree treated as its children. (In other words, the shadow host is treated as replacing the shadow root node.)
When considered within its own shadow trees, the shadow host is featureless. Only the :host, :host(), and :host-context() pseudo-classes are allowed to match it.
Tests
- host-descendant-003.html (live test) (source)
- host-is-006.html (live test) (source)
- host-is-featureless.html (live test) (source)
- host-multiple-002.html (live test) (source)
- host-multiple-003.html (live test) (source)
- host-multiple-004.html (live test) (source)
- host-multiple-005.html (live test) (source)
- host-not-001.html (live test) (source)
Why is the shadow host so weird?
The shadow host lives outside the shadow tree, and its markup is in control of the page author, not the component author.
It would not be very good if a component used a particular class name internally in a shadow tree stylesheet, and the page author using the component accidentally also used the same class name and put it on the shadow host. Such a situation would result in accidental styling that is impossible for the component author to predict, and confusing for the page author to debug.
However, there are still some reasonable use-cases for letting a stylesheet in a shadow tree style its shadow host. (For example, the component might want to be laid out as a flexbox, requiring the shadow host to be set to display: flex.) So, to allow this situation but prevent accidental styling, the shadow host appears but is completely featureless and unselectable except through :host and its related functional forms, which make it very explicit when you’re trying to match against markup provided by the page author.
Tests
- host-with-default-namespace-001.html (live test) (source)
- host-context-parsing.html (live test) (source)
- host-defined.html (live test) (source)
- host-is-001.html (live test) (source)
- host-is-002.html (live test) (source)
- host-is-003.html (live test) (source)
- host-is-004.html (live test) (source)
- host-is-005.html (live test) (source)
- host-parsing.html (live test) (source)
- scope-pseudo-in-shadow.html (live test) (source)
3.2.3. Selecting Into the Light: the :host, :host(), and :host-context() pseudo-classes
The :host pseudo-class, when evaluated in the context of a shadow tree, matches the shadow tree’s shadow host. In any other context, it matches nothing.
The :host() function pseudo-class has the syntax:
:host( <compound-selector> )
When evaluated in the context of a shadow tree, it matches the shadow tree’s shadow host if the shadow host, in its normal context, matches the selector argument. In any other context, it matches nothing.
The specificity of :host is that of a pseudo-class. The specificity of :host() is that of a pseudo-class, plus the specificity of its argument.
Note: This is different from the specificity of similar pseudo-classes, like :is() or :not(), which only take the specificity of their argument. This is because :host is affirmatively selecting an element all by itself, like a "normal" pseudo-class; it takes a selector argument for syntactic reasons (we can’t say that :host.foo matches but .foo doesn’t), but is otherwise identical to just using :host followed by a selector.
<x-foo class="foo">
<"shadow tree">
<div class="foo">...</div>
</>
</x-foo>
For a stylesheet within the shadow tree:
-
:host matches the
<x-foo>element. -
x-foo matches nothing.
-
.foo matches only the
<div>element. -
.foo:host matches nothing
-
:host(.foo) matches the
<x-foo>element.
Ordinary, selectors within a shadow tree can’t see elements outside the shadow tree at all. Sometimes, however, it’s useful to select an ancestor that lies somewhere outside the shadow tree, above it in the document.
The :host-context() functional pseudo-class tests whether there is an ancestor, outside the shadow tree, which matches a particular selector. Its syntax is:
:host-context( <compound-selector> )
When evaluated in the context of a shadow tree, the :host-context() pseudo-class matches the shadow host, if the shadow host or one of its shadow-including ancestors matches the provided <compound-selector>. In any other context, it matches nothing.
The specificity of :host-context() is that of a pseudo-class, plus the specificity of its argument.
Note: This means that the selector pierces through shadow boundaries on the way up, looking for elements that match its argument, until it reaches the document root.
Tests
- css-scoping-shadow-host-functional-rule.html (live test) (source)
- css-scoping-shadow-host-namespace.html (live test) (source)
- css-scoping-shadow-host-rule.html (live test) (source)
- host-context-specificity-001.html (live test) (source)
- host-context-specificity-002.html (live test) (source)
- host-context-specificity-003.html (live test) (source)
- host-descendant-001.html (live test) (source)
- host-descendant-002.html (live test) (source)
- host-descendant-invalidation.html (live test) (source)
- host-dom-001.html (live test) (source)
- host-functional-descendant-invalidation.html (live test) (source)
- host-has-internal-001.html (live test) (source)
- host-has-internal-002.html (live test) (source)
- host-has-internal-003.html (live test) (source)
- host-has-internal-004.html (live test) (source)
- host-in-host-context-selector.html (live test) (source)
- host-in-host-selector.html (live test) (source)
- host-multiple-001.html (live test) (source)
- host-nested-001.html (live test) (source)
- host-slotted-001.html (live test) (source)
- host-specificity-002.html (live test) (source)
- host-specificity-003.html (live test) (source)
- host-specificity.html (live test) (source)
- shadow-host-removal-invalidation.html (live test) (source)
- shadow-at-import.html (live test) (source)
- shadow-host-style-sharing.html (live test) (source)
- shadow-link-rel-stylesheet.html (live test) (source)
- shadow-shared-style-cache-001.html (live test) (source)
- stylesheet-title-001.html (live test) (source)
- stylesheet-title-002.html (live test) (source)
3.2.4. Selecting Slot-Assigned Content: the ::slotted() pseudo-element
The ::slotted() pseudo-element represents the elements assigned, after flattening, to a slot. This pseudo-element only exists on slots.
The ::slotted() pseudo-element is an alias for other elements in the tree, and does not generate any boxes itself.
The grammar of the ::slotted() pseudo-element is:
::slotted( <compound-selector> )
The ::slotted() pseudo-element represents the elements that are:
-
assigned, after flattening, to the slot that is ::slotted’s originating element
-
matched by its <compound-selector> argument
Tests
The ::slotted() pseudo-element can be followed by a tree-abiding pseudo-element, like ::slotted()::before, representing the appropriate pseudo-element of the elements represented by the ::slotted() pseudo-element.
Tests
The specificity of ::slotted() is that of a pseudo-element, plus the specificity of its argument.
<x-foo>
<div id="one" slot="foo" class="foo">...</div>
<div id="two" slot="foo">...</div>
<div id="three" class="foo">
<div id="four" slot="foo">...</div>
</div>
<"shadow tree">
<div id="five">...</div>
<div id="six">...</div>
<slot name="foo"></slot>
</"shadow tree">
</x-foo>
For a stylesheet within the shadow tree,
a selector like ::slotted(*)
selects #one and #two only,
as they’re the elements assigned to the sole slot element.
It will not select #three
(no slot attribute)
nor #four
(only direct children of a shadow host can be assigned to a slot).
A selector like ::slotted(.foo), on the other hand, will only select #one, as it matches .foo, but #two doesn’t.
Note: Note that a selector like ::slotted(*)
is equivalent to *::slotted(*),
where the * selects many more elements than just the slot element.
However, since only the slot elements are slots,
they’re the only elements with a ::slotted() pseudo-element as well.
Note: ::slotted() can only represent the elements assigned to the slot. Slots can also be assigned text nodes, which can’t be selected by ::slotted(). The only way to style assigned text nodes is by styling the slot and relying on inheritance.
3.2.5. Matching on the Presence of Slot-Assigned Nodes: the :has-slotted pseudo-class
The :has-slotted pseudo-class
matches slot elements
which have a non-empty list of flattened slotted nodes.
When :has-slotted matches a slot with fallback content, we can conclude that the fallback content is not being displayed.
Note: Even a single whitespace text node is sufficient to make :has-slotted' apply.
This is by design, so that the behavior of this pseudo-class is consistent with the behavior of the assignedNodes() method.
A future version of this specification is expected to introduce a way to exclude this case from matching.
Note: It is expected that a future version of this specification will introduce a functional :has-slotted() pseudo-class that allows more fine-grained matching by accepting a selector argument. :has-slotted is not an alias of :has-slotted(*), as the latter would not match slotted text nodes, but :has-slotted does.
Tests
- css-scoping-shadow-slotted-nested.html (live test) (source)
- css-scoping-shadow-slotted-rule.html (live test) (source)
- has-slotted-001.html (live test) (source)
- has-slotted-002.html (live test) (source)
- has-slotted-003.html (live test) (source)
- has-slotted-changing-001.html (live test) (source)
- has-slotted-changing-002.html (live test) (source)
- has-slotted-flattened-001.html (live test) (source)
- has-slotted-flattened-002.html (live test) (source)
- has-slotted-flattened-003.html (live test) (source)
- has-slotted-flattened-004.html (live test) (source)
- has-slotted-manual-assignment.html (live test) (source)
- has-slotted-query-selector.html (live test) (source)
- reslot-text-inheritance.html (live test) (source)
- slotted-invalidation.html (live test) (source)
- slotted-link.html (live test) (source)
- slotted-matches.html (live test) (source)
- slotted-nested.html (live test) (source)
- slotted-parsing.html (live test) (source)
- slotted-placeholder.html (live test) (source)
- slotted-slot.html (live test) (source)
- slotted-specificity-002.html (live test) (source)
- slotted-specificity.html (live test) (source)
- slotted-with-pseudo-element.html (live test) (source)
4. Shadow Trees and the Cascade
See CSS Cascading 4 § 6.1 Cascade Sorting Order.
4.1. Flattening the DOM into an Element Tree
While Selectors operates on the DOM tree as the host language presents it, with separate trees that are unreachable via the standard parent/child relationship, the rest of CSS needs a single unified tree structure to work with. This is called the flattened element tree (or flat tree), and is constructed as follows:
-
Let pending nodes be a list of DOM nodes with associated parents, initially containing just the document’s root element with no associated parent.
-
Repeatedly execute the following substeps until pending nodes is empty:
-
Pop the first element from pending nodes, and assign it to pending node.
-
Insert pending node into the flat tree as a child of its associated parent. (If it has no associated parent, it’s the document root—just insert it into the flat tree as its root.)
-
Perform one of the following, whichever is the first that matches:
- pending node is a shadow host
- Append the child nodes of the shadow root of the shadow tree it hosts to pending nodes, with pending node as their associated parent.
- pending node is a slot
-
Find slottables for pending node,
and append them to pending nodes,
with pending node as their associated parent.
If no slottables were found for pending node, instead append its children to pending nodes, with pending node as their associated parent.
- Otherwise,
- Append the child nodes of pending node’s light tree to pending nodes, with pending node as their associated parent.
-
Note: In other words, the flat tree is the top-level DOM tree, but shadow hosts are filled with their shadow tree children instead of their light tree children (and this proceeds recursively if the shadow tree contains any shadow hosts), and slots get filled with the nodes that are assigned to them (and this proceeds recursively if the slots are themselves assigned to a slot in a deeper shadow tree).
A non-obvious result of this is that elements assigned to a slot inherit from that slot, not their light-tree parent or any deeper slots their slot gets assigned to. This means that text nodes are styled by the shadow tree of their parent, with nobody else capable of intervening in any way. Do we want an additional pseudo-element for targeting those text nodes so they can be styled at all slot-assignment levels, like normal elements can be? This implies it needs to work for text nodes in the light tree before they’re assigned downwards, so this can’t just be a ::slotted() variant. Luckily, this is a long-standing request!
4.1.1. Slots and Slotted Elements in a Shadow Tree
Slots must act as if they were assigned display: contents via a rule in the UA origin. This must be possible to override via display, so they do generate boxes if desired.
Note: A non-obvious result of assigning elements to slots is that they inherit from the slot they’re assigned to. Their original light tree parent, and any deeper slots that their slot gets assigned to, don’t affect inheritance.
Tests
4.2. Name-Defining Constructs and Inheritance
Shadow trees are meant to be an encapsulation boundary, allowing independent authors to share code without accidentally polluting each other’s namespaces. For example, element IDs, which are generally meant to be unique within a document, can be validly used multiple times as long as each use is in a different shadow tree.
Similarly, several at-rules in CSS, such as @keyframes or @font-face, define a name that later at-rules or properties can refer to them by. Like IDs, these names are globally exposed and unique within a document; also like IDs, this restriction is now loosened to being unique within a given shadow tree.
However, property inheritance can carry values from one tree to another, which complicates referencing the correct definition of a given name. Done naively, this can produce surprising and confusing results for authors. This section defines a set of concepts to use in defining and referencing "global" names in a way that respects encapsulation and doesn’t give surprising results.
If an at-rule or property defines a name that other CSS constructs can refer to it by, such as a @font-face font-family name or an anchor-scope name, it must be defined as a tree-scoped name. Tree-scoped names are associated with the root of the element hosting the stylesheet that the at-rule or property is declared in.
Additionally, tree-scoped names can be loosely matched or strictly matched, defaulting to loosely matched unless otherwise specified. A loosely matched tree-scoped name can be matched by tree-scoped references (see below) in the same tree or descendant trees, while a strictly matched tree-scoped name can only be matched by tree-scoped references in the exact same tree.
Properties or descriptors that reference a tree-scoped name, such as the font-family or animation-name properties, must define their value as a tree-scoped reference. These references implicitly capture a node tree root along with their specified value: unless otherwise specified, the root of the element hosting the stylesheet that the property or descriptor is declared in. This root reference stays with the tree-scoped reference as it is inherited.
If a tree-scoped name is global (such as @font-face names), then when a tree-scoped reference is dereferenced to find it, first search only the tree-scoped names associated with the same root as the tree-scoped reference. If no relevant tree-scoped name is found, and the root is a shadow root, then repeat this search in the root’s host’s node tree (recursively). (In other words, global tree-scoped names “inherit” into descendant shadow trees, so long as they don’t define the same name themselves.)
If a tree-scoped name is local to an element (such as anchor-name or anchor-scope values), then whether a tree-scoped reference matches the tree-scoped name on a given element depends on whether the tree-scoped name is strictly or loosely matched. A strictly matched tree-scoped name only matches if both names are associated with the same tree. A loosely matched tree-scoped name also matches if the tree-scoped name is associated with an ancestor tree.
If two tree-scoped names are directly compared (for example, when comparing computed values), they are considered to match only if their identifiers match, and their roots match exactly. (If one has a root that’s an ancestor of the other, for example, they do not match.)
Global names include:
-
@font-face, referenced by font-family
-
@font-feature-values, referenced by font-family
-
@keyframes, referenced by animation-name
-
@counter-style, referenced by list-style-type
-
@color-profile, referenced by the color() function
-
@font-palette-values, referenced by font-palette
-
others?
For example, given the following document (using the imaginary <::shadow></::shadow> markup to indicate an element’s shadow tree):
< p class = outer > Here's some text in the outer document's "foo" font.< style > @ font-face { font-family : foo ; src : url ( https :// example . com / outer . woff ); } body { font-family : foo ; } my-component :: part ( text ) { font-family : foo ; } </ style > < my-component > < ::shadow > < p class = inner-default > I'm inheriting the outer document's font-family.< p class = inner-styled > And I'm explicitly styled to be in the component's "foo" font.< p class = part-styled part = text > I'm explicitly styled by the outer document, and get the outer document's "foo" font.< style > @ font-face { font-family : foo ; src : url ( https :// example . com / inner . woff ); } . inner-styled { font-family : foo ; } </ style > </ ::shadow > </ my-component >
The .outer element references the outer @font-face, using the "outer.woff" file.
The .inner-default element inherits the font-family: foo value from the outer document, using the same tree-scoped reference as .outer, and thus also uses the "outer.woff" font file.
The .inner-style element, on the other hand, receives a font-family: foo from the stylesheet inside the shadow, and thus its tree-scoped reference refers to the shadow’s @font-family, and it uses the "inner.woff" file.
The .part-styled element also receives its style from the outer document, tho by being directly set rather than by inheritance. Thus, its tree-scoped reference also refer’s to the outer document, and it uses the "outer.woff" file.
< style > @ font-face { font-family : foo ; src : url ( https :// example . com / outer . woff ); } body { font-family : foo ; } </ style > < child-component > < ::shadow > < style > @ font-face { font-family : foo ; src : url ( https :// example . com / inner . woff ); } </ style > < grandchild-component > < ::shadow > < p class = inner-default > I'm inheriting the outer document's "foo" font.</ p > < p class = inner-search > And I can't find a local "foo" font, so I'm searching further up the tree, and find the shadow's "foo" font.</ p > < style > . inner-search { font-family : foo ; } </ style > </ ::shadow > </ grandchild-component > </ ::shadow > </ child-component >
Here, just as in the previous example, .inner-default is inheriting the font-family: foo declared in the outer document, and so it ends up referencing the outer document’s @font-face, and is rendered with the "outer.woff" file.
On the other hand,
.inner-search receives its style from a stylesheet in <grandchild-component>’s shadow tree,
so it attempts to find a @font-face defining a foo font in that tree.
There is no such @font-face,
so it starts walking up the shadow trees,
finding an appropriate @font-face in <child-component>,
so it’s rendered with the "inner.woff" file.
Tests
- font-face-001.html (live test) (source)
- font-face-002.html (live test) (source)
- font-face-003.html (live test) (source)
- font-face-004.html (live test) (source)
- font-face-005.html (live test) (source)
- font-face-006.html (live test) (source)
- font-face-007.html (live test) (source)
- font-face-008.html (live test) (source)
- font-face-009.html (live test) (source)
- keyframes-003.html (live test) (source)
- keyframes-004.html (live test) (source)
- keyframes-005.html (live test) (source)
- keyframes-006.html (live test) (source)
- scoped-reference-animation-001.html (live test) (source)
- scoped-reference-animation-002.html (live test) (source)
4.2.1. Serialized Tree-Scoped References
If a tree-scoped reference is serialized, it serializes only its value; the associated root is lost.
This implies that `el.style.foo = getComputedStyle(el).foo;` is not necessarily a no-op, like it typically was before shadow trees existed.
For example, given the following document (using the imaginary <::shadow></::shadow> markup to indicate an element’s shadow tree):
< p class = outer > Here's some text in the outer document's "foo" font.< style > @ font-face { font-family : foo ; src : url ( foo . woff ); } body { font-family : foo ; } </ style > < my-component > < ::shadow > < p class = inner-default > I'm inheriting the outer document's font-family.< p class = inner-styled > And I'm explicitly styled to be in the component's "foo" font.< style > @ font-face { font-family : foo ; src : url ( https :// example . com / foo . woff ); } . inner-styled { font-family : foo ; } </ style > < script > const innerDefault= document. querySelector( '.inner-default' ); const innerStyled= document. querySelector( '.inner-styled' ); const defaultFont= getComputedStyle( innerDefault). fontFamily; const styledFont= getComputedStyle( innerStyled). fontFamily; console. log( defaultFont== styledFont); // true! </ script > </ ::shadow > </ my-component >
The .outer element is styled with the outer document’s "foo" @font-face.
The .inner-default element inherits font-family from the outer document,
meaning it inherits a tree-scoped reference
referencing that outer document,
and so it’s in the same font as .outer.
Meanwhile, .inner-styled is explicitly styled from inside the shadow root,
so it receives a fresh tree-scoped reference
referencing its shadow tree,
and it is instead styled the shadow’s own "foo" @font-face.
Despite that, the script running inside the component
sees the two elements as having the same value for font-family,
because the root-reference part of a tree-scoped reference
is not preserved by serialization.
If it were to set innerDefault
(thus setting the font-family property of the element’s attribute stylesheet,
which lives in the shadow tree),
the .inner-default element would suddenly switch
to the same font as .inner-styled!
Note: The [css-typed-om-1] is expected to reflect the root reference of a tree-scoped reference in its reification rules for values, allowing authors to tell what node tree the reference is taking its values from, and allowing values to be transported across node trees without changing their meaning.
5. Exposing a Shadow Element
Elements in a shadow tree may be exported for styling by stylesheets outside the tree using the part and exportparts attributes.Each element has a part name list which is an ordered set of tokens.
Each element has a forwarded part name list which is a list of tuples containing a string for the inner part being forwarded and a string giving the name it will be exposed as.
Each shadow root can be thought of as having a part element map with keys that are strings and values that are ordered sets of elements.
The part element map is described only as part of the algorithm for calculating style in this spec. It is not exposed via the DOM, as calculating it may be expensive and exposing it could allow access to elements inside closed shadow roots.
Part element maps are affected by the addition and removal of elements and changes to the part name lists and forwarded part name lists of elements in the DOM.
-
For each descendant el within outerRoot:
-
For each name in el’s part name list, append el to outerRoot’s part element map[name].
-
If el is a shadow host itself then let innerRoot be its shadow root.
-
Calculate innerRoot’s part element map.
-
For each innerName/outerName in el’s forwarded part name list:
-
If innerName is an ident:
-
Let innerParts be innerRoot’s part element map[innerName]
-
Append the elements in innerParts to outerRoot’s part element map[outerName]
-
-
If innerName is a pseudo-element name:
-
Append innerRoot’s pseudo-element(s) with that name to outerRoot’s part element map[outerName].
-
-
-
5.1. Motivation
For custom elements to be fully useful and as capable as built-in elements it should be possible for parts of them to be styled from outside. Exactly what can be styled from outside should be controlled by the element author. Also, it should be possible for a custom element to present a stable "API" for styling. That is, the selector used to style a part of a custom element should not expose or require knowledge of the internal details of the element. The custom element author should be able to change the internal details of the element while leaving the selectors untouched.
The previous proposed method for styling inside the shadow tree, the >>> combinator, turned out to be too powerful for its own good; it exposed too much of a component’s internal structure to scrutiny, defeating some of the encapsulation benefits that using Shadow DOM brings. For this, and other performance-related reasons, the >>> combinator was eventually dropped.
This left us with using custom properties as the only way to style into a shadow tree: the component would advertise that it uses certain custom properties to style its internals, and the outer page could then set those properties as it wished on the shadow host, letting inheritance push the values down to where they were needed. This works very well for many simple theming use-cases.
However, there are some cases where this falls down. If a component wishes to allow arbitrary styling of something in its shadow tree, the only way to do so is to define hundreds of custom properties (one per CSS property they wish to allow control of), which is obviously ridiculous for both usability and performance reasons. The situation is compounded if authors wish to style the component differently based on pseudo-classes like :hover; the component needs to duplicate the custom properties used for each pseudo-class (and each combination, like :hover:focus, resulting in a combinatorial explosion). This makes the usability and performance problems even worse.
We introduce ::part() to handle this case much more elegantly and performantly. Rather than bundling everything into custom property names, the functionality lives in selectors and style rule syntax, like it’s meant to. This is far more usable for both component authors and component users, should have much better performance, and allows for better encapsulation/API surface.
It’s important to note that ::part() offers absolutely zero new theoretical power. It is not a rehash of the >>> combinator, it is simply a more convenient and consistent syntax for something authors can already do with custom properties. By separating out the explicitly "published" parts of an element (the part element map) from the sub-parts that it merely happens to contain, it also helps with encapsulation, as authors can use ::part() without fear of accidental over-styling.
5.2. Naming a Shadow Element: the part attribute
Any element in a shadow tree can have a part attribute.
This is used to expose the element outside of the shadow tree.
Tests
The part attribute is parsed as a space-separated list of tokens representing the part names of this element.
Note: It’s okay to give a part multiple names. The "part name" should be considered similar to a class, not an id or tagname.
<style>
c-e::part(textspan) { color: red; }
</style>
<template id="c-e-template">
<span part="textspan">This text will be red</span>
</template>
<c-e></c-e>
<script>
// Add template as custom element c-e
...
</script>
5.3. Forwarding a Shadow Element: the exportparts attribute
Any element in a shadow tree can have a exportparts attribute.
If the element is a shadow host,
this is used to allow styling of parts from hosts inside the shadow tree
by rules outside this the shadow tree
(as if they were elements in the same tree as the host,
named by a part attribute).
Tests
The exportparts attribute is parsed as a comma-separated list of part mappings. Each part mapping is one of:
innerIdent : outerIdent-
Adds
innerIdent/outerIdentto el’s forwarded part name list. ident-
Adds
ident/identto el’s forwarded part name list.Note: This is shorthand for
ident : ident. ::ident : outerIdent-
If
::identis the name of a fully styleable pseudo-element, adds::ident/outerIdentto el’s forward part name list. Otherwise, does nothing. - anything else
-
Ignored for error-recovery / future compatibility.
Note: It’s okay to map a sub-part to several names.
<style>
c-e::part(textspan) { color: red; }
</style>
<template id="c-e-outer-template">
<c-e-inner exportparts="innerspan: textspan"></c-e-inner>
</template>
<template id="c-e-inner-template">
<span part="innerspan">
This text will be red because the containing shadow
host forwards innerspan to the document as "textspan"
and the document style matches it.
</span>
<span part="textspan">
This text will not be red because textspan in the document style
cannot match against the part inside the inner custom element
if it is not forwarded.
</span>
</template>
<c-e></c-e>
<script>
// Add template as custom elements c-e-inner, c-e-outer
...
</script>
exportparts attribute,
to masquerade as a ::part()
for the component it’s in:
<template id=custom-element-template>
<p exportparts="::before : preceding-text, ::after : following-text">
Main text.
</template>
An element using that template can use a selector like x-component::part(preceding-text) to target the p::before pseudo-element in its shadow, so users of the component don’t need to know that the preceding text is implemented as a pseudo-element.
5.4. Selecting a Shadow Element: the ::part() pseudo-element
The ::part() pseudo-element
allows you to select elements that have been exposed via a part attribute.
The syntax is:
::part() = ::part( <ident>+ )
Tests
The ::part() pseudo-element only matches anything when the originating element is a shadow host.
part="label"),
you can select it with
x-button::part(label).
A tabstrip control might have multiple elements
with part="tab",
all of which are selected by ::part(tab).
If a single tab is active at a time,
it can be specially indicated with part="tab active"
and then selected by ::part(tab active)
(or ::part(active tab), as order doesn’t matter).
The ::part() pseudo-element is a fully styleable pseudo-element. If the originating element’s shadow root’s part element map contains the specified <ident>, ::part() represents the elements keyed to that ident; if multiple idents are provided and the part element map contains them all, it represents the intersection of the elements keyed to each ident. Otherwise, it matches nothing.
::part() pseudo-elements inherit according to their position in the originating element’s shadow tree.
If the <x-panel>’s internal confirm button had used something like
part="label => confirm-label"
to forward the button’s internal parts up into the panel’s own part element map,
then a selector like
x-panel::part(confirm-label)
would select just the one button’s label,
ignoring any other labels.
5.5. Extensions to the Element Interface
partial interface Element { [SameObject ,PutForwards =value ]readonly attribute DOMTokenList ; };part
Tests
The part attribute’s getter must return a DOMTokenList object whose associated element is the context object and whose associated attribute’s local name is part. The token set of this particular DOMTokenList object are also known as the element’s parts.
Define this as a superglobal in the DOM spec. [w3c/csswg-drafts Issue #3424]
5.6. Microsyntaxes for parsing
5.6.1. Rules for parsing part mappings
A valid part mapping is a tuple of tokens separated by a U+003A COLON character and any number of space characters before or after the U+003A COLON The tokens must not contain U+003A COLON or U+002C COMMA characters.
The rules for parsing a part mapping are as follows:
-
Let input be the string being parsed.
-
Let position be a pointer into input, initially pointing at the start of the string.
-
Collect a sequence of code points that are space characters
-
Collect a sequence of code points that are not space characters or U+003A COLON characters, and let first token be the result.
-
If first token is empty then return error.
-
Collect a sequence of code points that are space characters.
-
If the end of the input has been reached, return the tuple (first token, first token)
-
If character at position is not a U+003A COLON character, return error.
-
Consume the U+003A COLON character.
-
Collect a sequence of code points that are space characters.
-
Collect a sequence of code points that are not space characters or U+003A COLON characters. and let second token be the result.
-
If second token is empty then return error.
-
Collect a sequence of code points that are space characters.
-
If position is not past the end of input then return error.
-
Return the tuple (first token, second token).
5.6.2. Rules for parsing a list of part mappings
A valid list of part mappings is a number of valid part mappings separated by a U+002C COMMA character and any number of space characters before or after the U+002C COMMA
The rules for parsing a list of part mappings are as follow:
-
Let input be the string being parsed.
-
Split the string input on commas. Let unparsed mappings be the resulting list of strings.
-
Let mappings be an initially empty list of tuples of tokens. This list will be the result of this algorithm.
-
For each string unparsed mapping in unparsed mappings, run the following substeps:
-
If unparsed mapping is empty or contains only space characters, continue to the next iteration of the loop.
-
Let mapping be the result of parsing unparsed mapping using the rules for parsing part mappings.
-
If mapping is an error then continue to the next iteration of the loop. This allows clients to skip over new syntax that is not understood.
-
Append mapping to mappings.
-
6. Changes
The following significant changes were made since the 3 April 2014 Working Draft.
-
Defined that tree-scoped names inherit into descendant shadow trees
-
Renamed ::content to ::slotted.
-
Define the flattened tree.
-
Generally reorg and rebase the Shadow DOM section on top of current DOM.
-
Punt @scope and related things, and ::region and related things, to the next level of the draft.
-
Define the specificity of :host, :host(), :host-context(), and ::slotted()
-
Remove the >>> (previously called /deep/) combinator.
-
Define that tree-abiding pseudos are allowed after ::slotted().
-
Allow <compound-selector-list> in all the pseudos.
-
Define a way to create a stylesheet of default element styles for a given element.
-
Make featureless elements match nothing.
-
Define in the context of a shadow tree.
-
Merged [css-shadow-parts] and renamed the specification to CSS Shadow Module Level 1. (Issue #5809)
-
Added support for multiple names in ::part()
-
Renamed 'part name map' to forwarded part name list
-
Restructured 'part element list' algorithm
-
Moved various ::part() details to fully styleable pseudo-element
-
Added Web Platform Tests coverage
-
Minor editorial improvements
7. Privacy Considerations
This specification introduces Shadow DOM and some shadow-piercing capabilities, but this does not introduce any privacy issues —shadow DOM, as currently specified, is intentionally not a privacy boundary (and the parts of the UA that use shadow DOM and do have a privacy boundary implicitly rely on protections not yet specified, which protect them from the things defined in this specification).
8. Security Considerations
This specification introduces Shadow DOM and some shadow-piercing capabilities, but this does not introduce any security issues —shadow DOM, as currently specified, is intentionally not a security boundary, merely a convenience for page authors. Exposing shadow trees to selectors in this way introduces no new security considerations. (And the parts of the UA that use shadow DOM and do have a security boundary implicitly rely on protections not yet specified, which protect them from the things defined in this specification).