I wanted to see if I could use a web component to override the styles for a given element:
<x-component>
<p>Hello World</p>
</x-component>
Turns out you can’t! (At least, you shouldn’t…)
That’s because by slotting content you’re not moving it from the light DOM to the shadow DOM. The nodes physically stay where they are, they’re just reflected inside the web component. This also means that global document styles still apply.
https://www.matuzo.at/blog/2022/100daysof-day45
This is because of encapsulation contexts:
… without
https://tomherni.dev/blog/the-specificity-of-slotted/!important
, a web component’s::slotted()
rules are overridden by the outer context (global styles). Specificity pretty much goes out the window.
So if you really, really need to override slotted styles… it is technically possible with !important
. Here’s an example: https://codepen.io/tannerhodges/pen/JoPmjbr
<style>
/* HACK: Reset global styles for slotted content. */
:host,
::slotted(*) {
all: initial !important;
}
</style>
🙈 Please don’t use this in production.