A simple carousel with a few lines of CSS
A few years back, I built Siema — a lightweight (only 3kb gzipped) carousel plugin with no dependencies. It became massively popular because of its simplicity and extensibility. I’m proud of this project because not only helped me but also many other developers.
CSS nowadays is so powerful, and if you need a simple carousel, I would like to kindly ask you not to use Siema (or any other carousel library) anymore. Using CSS is more straightforward, accessible, feels more natural and the browser support for scroll snap is great. Have a look at this minimalistic example.
ul {
display: flex;
list-style: none;
overflow: auto;
scroll-snap-type: x mandatory;
}
li {
flex-shrink: 0;
width: 100%;
scroll-snap-align: start;
}
See the Pen Super simple CSS carousel by Pawel Grzybek (@pawelgrzybek) on CodePen.
This article is just a quick note to my future self to come here and copy/paste what I need, but if you found it useful, I am super happy. I can assure you that the next major release of Siema will come with a lot less JavaScript (0kb). Bye 👋
I guess it‘s not a full replacement for Siema if you think about:
How would you do that?
Yeah I know it isn't a direct replacement, thats why I said " if you need a simple carousel". There is an API t interact with scrollable areas, but I don't know it yet. One day maybe I will write a post about it. Good suggestion!
Thanks! I guess you could come up with a light weight version of Siema that makes use of scroll snap but also provides programmatic controls. All it’d do is to change the scroll position and the browser would do the rest :)
I think this is awesome. I will also take my time to understand it and determine the possibility of buttons without without unnecessary complicating the code.
Well done.
Argyle Adam, in his GUI Challenges series, made a carousel using CSS scroll snapping. His demo page has maaany variants, most with buttons and other means of interacting with the carousel.
https://gui-challenges.web.app/carousel/dist/
I haven't really checked the source yet, but it seems he just used simple javascript to code those interactions
Nice, but you might want to add some things to make keyboard-accessible:
aria-label
is just in case screen reader users are wondering why it's focusable.Wait a sec. Is it still going to be focusable after adding
tabindex="0"
?It's not focusable now. Adding the
tabindex="0"
is so that it will be.