This is the first in a series of posts about writing CSS for HTML based on the content of selectors and not just the selectors themselves.
-hitch-has()
Imagine you have the following markup:
<p>Text is red because <span class="fast">of this SPAN.</span></p> <p>Text is green because <span class="slow">of this SPAN.</span></p>
In the first paragraph it would be nice to make the text red because it has a SPAN with a class of “fast”. In the second it would be nice to make it green because it has a SPAN with a class of “slow”. We want this:
Text is red because of this SPAN.
Text is green because of this SPAN.
So let’s try to write CSS to achieve this:
p span.fast { color: red; } p span.slow { color: green; }
Nope. That won’t work. Hmmm. How about:
p > span.fast { color: red; } p > span.slow { color: green; }
That’s not it either. The reason is in how CSS works natively. CSS selectors are intended to find a single element or a set of elements. But once that selector is matched there is no way to traverse up or down the DOM for anything else to base the match on. What we want is to say “find a P element that has a SPAN element with a CLASS”. That’s currently not doable in native CSS.
Hitch provides -hitch-has() and here’s the answer:
p:-hitch-has(span.fast) { color: red; } p:-hitch-has(span.slow) { color: green; }
Doesn’t that feel better? Take a look at Hitch for more expressive CSS!
Note: Hitch is a rather new project. It has amazing potential and also a few things yet to be built. It’s open sourced and available on Github: https://github.com/bkardell/Hitch/. Fork it. Change how CSS works!
In CSS4, you can traverse up the DOM tree. See http://www.w3.org/TR/2011/WD-selectors4-20110929/#subject
Your example could be accomplished using the following CSS:
$p span.fast { color: red; }
$p span.slow { color: green; }
Yep. But that isn’t necessarily supported in all of the browsers. With Hitch you can opt-in to that feature while the standard progresses and the UA vendors begin to implement it.
Yes, it will be a great day if we ever get these abilities in CSS itself! That said, this (:has) was first proposed more than a decade ago, but it got pushed out to CSS Selectors Level 4 in the limited form you show above (less powerful than the original :has). It is also not implemented by any browser and if you watch the lists, it would appear to be at risk of being dropped/pushed to selectors level 5.
Isn’t this basically CSS4’s subject selector? http://www.w3.org/TR/2011/WD-selectors4-20110929/#subject
I was too late ^^
Pingback: Content based CSS: -link-* | Hitch JS