Content based CSS: -hitch-has

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!

About these ads

6 thoughts on “Content based CSS: -hitch-has

    • 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.

  1. 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.

  2. Pingback: Content based CSS: -link-* | Hitch JS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s