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_p = document.createElement( "p" ),
shadow = new_div.attachShadow( { mode: "open" } );
new_style.textContent = `p {
padding: 1em;
border-radius: 1em;
box-shadow: 2px 2px 15px 5px rgba( 0, 0, 0, .5 );
}`;
shadow.appendChild( new_style );
new_p.textContent = "Shadow DOM FTW \\o/";
shadow.appendChild( new_p );
new_div.style.all = "unset";
document.body.appendChild( new_div );
body {
background: antiquewhite;
}
div {
background: cornflowerblue;
border: 2px grey solid;
border-right: 0;
border-left: 0;
margin: 2em;
}
p {
font-family: "Comic Sans MS";
margin: inherit;
}
<body>
<div><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></div>
</body>