Element Queries: Prollyfilled

Smashing Magazine recently tweeted about two Blog articles: Responsive Containers by Andy Hume  and Media Queries Are A Hack by Ian Storm Taylor  basically arguing that media queries are not enough, we need “element queries”.  Fortunately, our friend François REMY had proposed something like this to the CSS Working Group and based on some work with Mozilla’s Daniel Buchner has created a prollyfill with HitchJS to let you use them now, fork it, provide feedback and help make the Web a better place for us all.

Download the latest version of HitchJS, mark one of your stylesheets with the data-hitch-interpret flag, require it and get rolling:

For a quick look at the basic proposal, see the draft in the HitchJS Repo – for a more in-depth look, check out his article on Element Query prollyfilling/concepts.

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!