Shadow DOM
The feature(s) of the Shadow DOM v1
currently (constantly subject to change) have growing support, offering a wealth of possibilities, including scoped CSS.
Shadow DOM v0
was implemented in Chrome/Opera but other browser vendors are implementing v1
.
MS Edge status: Under Consideration
Firefox status: in-development
From Google Developers: Shadow DOM v1: Self-Contained Web Components:
Hands down the most useful feature of shadow DOM is scoped CSS:
- CSS selectors from the outer page don't apply inside your component.
- Styles defined inside don't bleed out. They're scoped to the host element.
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.
Below, we attachShadow
to a new createElement( "div" )
to which we apply the style.all = "unset"
to disinherit all
the rules applied to the rest of the document
's div
s.
We then fill our shadow-root
with whatever content we like, and supply any styles desired, before appendChild( "new_div" )
injects our content into the body
.
The result is stylistically isolated content.
const new_style = document.createElement( "style" ),
new_div = document.createElement( "div" ),
new_list = document.createElement( "ul" ),
new_entries = [ "Lorem", "Ipsum", "Dolor" ],
shadow = new_div.attachShadow( { mode: "open" } );
new_style.textContent = "ul { list-style: none; }";
new_div.style.all = "unset";
new_entries.forEach( ( v ) => {
var li = document.createElement( "li" );
li.textContent = v;
new_list.appendChild( li );
} );
shadow.appendChild( new_style );
shadow.appendChild( new_list );
document.body.appendChild( new_div );
body {
background: antiquewhite;
}
ul {
margin: 2em;
border: 2px gray solid;
border-right: 0;
border-left: 0;
background: cornflowerblue;
}
li {
margin: inherit;
font-family: "Comic Sans MS";
}
<body>
<ul>
<li>Foo</li>
<li>Bar</li>
<li>Baz</li>
<li>Qux</li>
</ul>
</body>