Styling: Styles Piercing Shadow DOM
"Doesn't shadow DOM provide total encapsulation?"
Nope! As written in the spec:
The top-level elements of a shadow tree inherit from their host element.
What this means is that inheritable styles, like color
or font-family
among others, continue to inherit in shadow DOM, will pierce the shadow DOM and affect your component's styling.
Custom CSS properties are also able to pierce the shadow DOM boundary, and can be used to style elements from outside of your component itself. Example:
/* define: */
html {
--owc-blue: #217ff9;
}
/* use inside your component: */
:host {
background-color: var(--owc-blue);
}
If this inheriting behavior is undesirable, you can reset it by adding the following CSS to your component:
:host {
/* Reset specific CSS properties */
color: initial;
/* Reset all CSS properties */
all: initial;
}
Do note that setting all: initial;
will not reset CSS custom properties. If for some reason you find yourself needing to reset a specific property, you must specify it explicitly.
You can find a code example here.
If you're interested in reading more about this, you can check out these resources: