DOM - Shadow DOM (Scoped DOM)
About
The Shadow DOM is the part of the DOM that is:
- written by the DOM engine (generally the Browser)
- and not by the user.
Note: the light DOM represents all DOM custom element
The Shadow DOM provides a way:
- for an custom element to own, render, and style a chunk of DOM that's separate from the rest of the page. This is a scope functionality
An iframe offers also scope functionalities but the shadow dom offers more features.
Why
When the scope is global:
- new HTML id/class may conflict with an existing name
- CSS styling rule becomes then a huge issue (The !important rule becomes the rule), style selectors grow out of control, and performance can suffer.
Example
custom HTML fancy-tabs creating tabs in a shadow dom (Adapted from source) - Hover on the result and click the try the code button to see the code.
Styling
Scoped
CSS selectors (In stylesheets or inline ) used inside shadow DOM apply only locally. Outer CSS selectors does not apply by default into a shadow dom.
<link rel="stylesheet" href="styles.css">
<style>
#panels {
box-shadow: 0 2px 2px rgba(0, 0, 0, .3);
background: white;
...
}
#tabs {
display: inline-flex;
...
}
</style>
Styling the shadow element
- Shadow DOM custom components can style themselves too, by using the :host selector.
<style>
:host {
display: block; /* by default, custom elements are display: inline */
contain: content; /* CSS containment FTW. */
}
</style>
Outer Styling
Example with the following html
<body class="darktheme">
<fancy-tabs>
...
</fancy-tabs>
</body>
The below :host-context(.darktheme) CSS selector will style <fancy-tabs> because it's a descendant of the .darktheme class.
:host-context(.darktheme) {
color: white;
background: black;
}
Hook
hooks are CSS custom properties