Title: CSS Scoping Module Level 1
Level: 1
Shortname: css-scoping
Group: CSSWG
Status: ED
Work Status: Exploring
TR: https://www.w3.org/TR/css-scoping-1/
ED: https://drafts.csswg.org/css-scoping/
Previous Version: https://www.w3.org/TR/2014/WD-css-scoping-1-20140403/
Editor: Tab Atkins Jr., Google, http://xanthir.com/contact/, w3cid 42199
Abstract: This specification defines scoping/encapsulation mechanisms for CSS, focusing on the Shadow DOM scoping mechanism.
Ignored Terms: inherit, slot, custom elements, stylesheets
Ignored Vars: root elements

Introduction

...

Default Styles for Custom Elements

Advisement: 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. {{Window}}s 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. Issue: 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.

Shadow Encapsulation

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 [[SELECTORS4#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.

Shadow DOM and Selectors

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. Issue: 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.
For example, any selector in a stylesheet embedded in or linked from an an element in a shadow tree is in the context of a shadow tree. So is the argument to {{querySelector()}} when called from a shadow root.
Declarations inherit the tree context of the selector that was matched to apply them.

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.
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 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.

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( <> )
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 '':matches()'' 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.
For example, say you had a component with a shadow tree like the following:
			<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.
For example, a group of components can define a handful of color themes they they know how to respond to. Page authors could opt into a particular theme by adding a specific class to the components, or higher up 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( <> )
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 <>. 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.

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( <> )
The ''::slotted()'' pseudo-element represents the elements that are: * assigned, after flattening, to the slot that is ''::slotted''’s originating element * matched by its <> argument 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. The [=specificity=] of ''::slotted()'' is that of a pseudo-element, plus the [=specificity=] of its argument.
For example, say you had a component with both children and a shadow tree, like the following:
			<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.

Shadow Trees and the Cascade

To address the desired cascading behavior of rules targetting elements in shadow roots, this specification extends the cascade order defined in the Cascade specification. [[!CSS3CASCADE]] An additional cascade criteria must be added, between Origin and Scope, called Shadow Tree. * When comparing two declarations that have different tree contexts, then for normal rules the declaration earlier in the shadow-including tree order wins, and for important rules the declaration coming later in the shadow-including tree order wins. Note: This is the opposite of how scoped styles work.

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: 1. Let pending nodes be a list of DOM nodes with associated parents, initially containing just the document's root element with no associated parent. 2. Repeatedly execute the following substeps until pending nodes is empty: 1. Pop the first element from pending nodes, and assign it to pending node. 2. 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.) 3. 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). Issue: 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!

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.

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-family!!descriptor' name or an ''@keyframes'' name, it must be defined as a tree-scoped name. [=Tree-scoped names=] are "global" within a particular [=node tree=]; unless otherwise specified, they're associated with the [=root=] of the [=element=] hosting the stylesheet that the at-rule or property is defined in. Properties or descriptors that reference a "global" name, such as the 'font-family!!property' or 'animation-name' properties, must define their value as a tree-scoped reference. [=Tree-scoped 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 defined in. This [=root=] reference stays with the [=tree-scoped reference=] as it is inherited. Whenever a [=tree-scoped reference=] is dereferenced to find the CSS construct it is referencing, only the [=tree-scoped names=] associated with the same [=root=] as the [=tree-scoped reference=] must be searched.
TODO: Fix all the at-rules that define global names, and the properties that reference them, to use these concepts. * ''@font-face'', referenced by 'font-family!!property' * ''@font-feature-values'', referenced by 'font-family!!property' * ''@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?

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> 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); } .outer { 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.style.fontFamily = defaultFont; (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.

Changes

The following significant changes were made since the 3 April 2014 Working Draft. * 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. Privacy and Security Considerations {#priv-sec} =============================================== This specification introduces Shadow DOM and some shadow-piercing capabilities, but this does not introduce any privacy or security issues-- shadow DOM, as currently specified, is intentionally not a privacy/security boundary (and the parts of the UA that use shadow DOM and do have a privacy/security boundary implicitly rely on protections not yet specified, which protect them from the things defined in this specification).