
Member-only story
HOW TO: Pure CSS “carousel”
Thinking CSS first again with the return of the sibling combinator
The carousel can be pretty daunting. There are so many options, features, devices/browsers to please. Do you even need a carousel? 😕
“No!!! Seriously, you really shouldn’t” — shouldiuseacarousel.com(love the inline comments in the markup, check the
console
😂)
If you decide you need a carousel, you don’t have to create one yourself. You might look at slick carousel or something from a large UI framework such as Bootstrap.
And this is where the disclaimer comes in 👉 If you’re looking for a feature rich carousel, a pure CSS
“carousel”(heavy emphasis on the quotes) is not for you. You can close the browser tab, continue with your carousel and most likely no kittens will come to harm 😉
For those intrigued or looking to save kittens, let’s explore! 🔍
For those in camp TL;DR, Here’s a demo!
https://codepen.io/jh3y/pen/WwVKLN
A background for pure CSS components
Doing things in pure CSS
as opposed to with a hint of JavaScript
is not something new. I’ve written before about thinking CSS first.
The capability to create this “carousel” example isn’t something new that’s sprung up. A new CSS
feature hasn’t landed. What it is, is another case of thinking outside the box a little and getting CSS
to do more heavy lifting for us. Most pure CSS
tricks come from observing how elements respond to user interaction 😎
The most simple pure CSS
solution most will be familiar with is to show something like a tooltip or a menu. Hover state provides an opportunity to alter render state without touching any JavaScript
.
The “carousel” trick 🎩
So, what’s the trick for getting this “carousel” to work?
The use of the label
element in combination with input
elements of type radio
. In particular we leverage the for
and checked
attributes of each. We use the sibling combinator(~
) and preprocessor looping. We can use these to generate nth-of-type
selectors for the number of slides we are showing.