Archive for February, 2016

Three-way CSS-only selector

Thursday, February 11th, 2016

I was at the Slovenian CSS Meetup yesterday where I did a short talk on Quantity Queries. That’s a name given to a technique where you use pseudo class selectors to discern how many elements are inside a certain element – for example :first-child:nth-last-child(4) {} will only select the first child if there are exactly 4 elements. If you group that with the general sibling selector ~, you can also get all the other elements.

The idea of quantity queries has been around for a year or so and even though at first glance you might say “We’ve got flexbox for that now”, you’d only be right in certain cases. The thing that quantity queries bring to the table is the idea of being able to change the styling depending on the number of elements, which I guess people currently solve either on the backend or with javascript.

But that’s not the main reason I’m writing this – it’s the last talk of the night where a three-way selector solution was presented by Gorazd. He created a CSS version but had problems with the smoothness of the animation as he didn’t know where the selector was before the selection to move it to the selected position after a user interaction. He resorted to using javascript that basically only did some class switching. This immediately gave me an idea that a sibling selector could be used for that if the indicator had the same parent as the inputs and was positioned after them in the code. And today I made a proof-of-concept solution I’m calling “the three-way CSS-only selector”.

It uses three radio buttons, so the form is perfectly submittable, the labels also select properly, it animates properly and does not use javascript. It’s only been tested on the browsers I have on my Mac, so I can easily see it breaking in IE or mobile browsers – if anyone wants to fix that please go ahead and ping me to add your solution to this post. You can also check the solution on JSBin.