Can Shadow DOM elements inherit CSS?

anderspitman picture anderspitman · Aug 8, 2014 · Viewed 7.2k times · Source

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?

Answer

Pointy picture Pointy · Aug 8, 2014

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.


In a complete Shadow DOM implementation, CSS has a ::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; }