Casey Casey - 1 year ago 66
CSS Question

Using :host-context() with an adjacent sibling selector

I'm trying to use :host-context() and adjacent sibling selectors to style an element like this:

<x-foo id="1" active></x-foo>
<x-foo id="2"></x-foo> <!-- use :host-context() to target #2 when adjacent sibling, #1 is [active] -->
<x-foo id="3"></x-foo>

My element definition looks something like:

<dom-module id="x-foo">
:host-context(x-foo[active] + x-foo) {
background-color: yellow;
<script src="x-foo.js"></script>

However this doesn't quite work. Why not?

Answer Source

:host() and :host-context() only accept a compound selector as their argument, and not a complex selector.

x-foo[active] + x-foo is a complex selector that contains two compound selectors, x-foo[active] and x-foo, separated by the adjacent sibling combinator. :host() and :host-context() can accept either compound selector, but not any combinators.

Unfortunately, because the shadow host's siblings do not exist in the shadow context, you won't be able to write something like x-foo[active] + :host. As a consequence, I don't think you will be able to accomplish what you're looking to do in a shadow context. (In the light context, of course, you can just write x-foo[active] + x-foo, but that defeats the purpose of prepackaging CSS into a web component.)

It's not clear to me why :host() and :host-context() weren't specced to allow complex selectors in the first place, since if they did, what you have would have just worked.