Kilian Valkhof

Building tools that make developers awesome.

Hocus pocus: custom selectors

CSS & HTML, 9 February 2016, 2 minute read

Here’s an update on my preferred :hocus selector. It’s now possible! …In PostCSS, and possibly in browsers in the future!

Two years ago, I tweeted out a lament on always having to type both :hover and :focus:

I'm tired of always having to type 'a:hover, a:focus {}', I therefore propose a new pseudo class that combines them: a:hocus {}

— Kilian Valkhof (@kilianvalkhof) January 31, 2014

You can read more about it in the earlier post. I’m glad to tell you it’s been two years and writing :hocus is now a thing you can do …In PostCSS, and possibly in browsers in the future! One of the replies I got on my tweet was about a new CSS specification: the CSS Aliases spec. Back then, it wasn’t yet done (let alone implemented) and had a slightly different syntax than it does now. It contained something called “custom selectors“.

Using custom selectors #

This spec allows you to define your own selector as an alias for a list of other selectors. This works for any selector, so we can create a custom selector that combines :hover and :focus.

Here’s the (pretty simple) syntax:

@custom-selector :--hocus :hover, :focus;

a:--hocus {
  /* hover and focus! */
  color:red;
}

Isn’t that great? Apart from the fact that it’s not implemented yet. Luckily we have a solution for that!

Do you want a better understanding of your own CSS selectors? Then check out the CSS specificity calculator that explains your selectors.

CSSNext #

Before explaining CSSNext, you need to know what PostCSS is: PostCSS is a system that allows you to easily transform CSS styles. PostCSS by itself does nothing, but you can add plugins to do all sorts of transformations.

CSSNext is the plugin that allows you to write CSS according to the latest specifications (if possible) so you can see what the future of CSS holds.

And one of the proposed features custom selectors.

Playground #

Setting up PostCSS and NextCSS takes some work, with choosing a runner and configuring it. There’s plenty of tutorials available online so I’m not going to attempt to help with setting it up, but for PostCSS check their Readme for a number of options and once you have that running, install and add the postcss-cssnext plugin.

If that’s all too much of a hassle and you just want to try it out (like any sane person) CSSNext has a playground that you can try out new syntax in and see what CSS it transforms into. Copy in the above css and see!

I’m very glad to see that CSS as a language is improving not just in features but also in ways to make it easier for developers to work with. I’m also very happy I can now use :--hocus!

Polypane browser for responsive web development and design Hi, I'm Kilian. I make Polypane, the browser for responsive web development and design. If you're reading this site, that's probably interesting to you. Try it out!