I was listening to this episode of JavaScript Jabber:
http://javascriptjabber.com/120-jsj-google-polymer-with-rob-dodson-and-eric-bidelman/
At one point Rob says:
And everyone has this first inclination, because it makes so much sense. You’re like, “Bootstrap is components. I’m just going to make them into tags.” But then you run into the fact that the Bootstrap style sheet is just one big long style sheet that was written assuming that it could touch every part of the document. And when you are suddenly scoping bits of the markup, scoping it so that the CSS can’t reach it, the CSS would actually have to be in the Shadow DOM with it and you would have to write that element from the ground up, that’s where people I think get really confused and really frustrated initially.
This made me wonder, how would you solve this problem with Web Components? Is there a way for Shadow DOM templates to inherit common styles, or would you have to repeat shared CSS for each separate component? Or something else?
Note: the substance of the answer below is no longer relevant, as the features discussed have been deprecated for some time. Don't use the sample code, but feel free to take a peek into the Internet past.
::shadow
pseudo-class, and also the /deep/
combinator.
The ::shadow
pseudo-class lets you break into the shadow DOM under an element, and it matches the shadow root. The /deep/
combinator effectively opens up the shadow DOM completely.
Thus, if you had a <x-foo>
element with <span>
elements inside, you could make them red with
x-foo::shadow span { color: red; }
Or make all <spans>
in any shadow DOM red:
body /deep/ span { color: red; }
Whatever hacks were necessary in the past, the current state of the shadow dom / CSS is that you can link to external stylesheets. More info at MDN: https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM#Internal_versus_external_styles
You could, then, have some sort of utility stylesheet (Tailwind or similar) that all of your components reference, so you don't duplicate CSS. In theory, that CSS file would get downloaded once, cached, and then the custom elements would each be able to use the classes in it (as long as they each link to it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With