A Possible Future for CSS Selectors

Share

A Possible Future for CSS Selectors

Woolly, the CSS sheep.

CSS has some great new tools like pseudo classes and pseudo elements for selecting things just by where they are in the DOM. For example, :first-child can select the first descendant of an element or ::first-letter can select the first letter of a sentence.

Even handier are the "::nth" selectors, which allow you specify arbitrary positions for selectors like :nth-child or :nth-of-type.

In fact, the ::nth selectors for pseudo classes and pseudo elements are so handy you might wonder why there isn't just an ::nth for everything. That's exactly what developer Chris Coyier calls for over at CSS-Tricks, saying that CSS should broaden the scope of ::nth to include, well, everything.

Among the possibilities with additional ::nth selectors are fancy typography effects like what Lettering.js can do (but without the JavaScript) or something a seeming simple as pure CSS line numbers.

While many of Coyier's examples are undeniably great tools, they are also fraught with problems. For example the suggested ::nth-line would be entirely dependent on the current page layout. Even something as simple as resizing a window would require the browser to recalculate the rule adding a possibly significant performance overhead. Similarly ::nth-word becomes much more complex than it sounds when you take linguistic variations into account (just what constitutes a word varies considerably by language, CSS has to account for all those variations).

On the other hand a subsequent discussion on the W3C CSS Working Group mailing list has been somewhat positive about Coyier's ::nth-letter suggestion. Indeed ::nth-letter is perhaps the most useful of Coyier's suggestions, but even if it did make it into the CSS specification that's no guarantee browsers would actually implement it.

As Coyier points out, this isn't the first time someone has suggested adding ::nth for additional elements, Anne van Kesteren called for something similar back in 2003, which doesn't give one high hopes for getting even ::nth-letter() in this time around. Still, a developer can dream.