Recently, I was doom-scrolling twitter when I came across a tweet that claimed that you can build an image carousel using just two lines of CSS. I liked the tweet and then thought to myself “I can’t sleep, right now. Why not try it out?”
CSS Tip 💡
Create image Carousel using two lines of CSS. pic.twitter.com/PLIyTaXZkV
— Pratham (@Prathkum) February 10, 2022
It turned out that I needed a few more than two lines of CSS, but it was still somewhat simple.
So, what’s going on in the pen? There is a slides div that scrolls horizontally, slide divs that have background images that fill the div, and both divs fill 100% of the width and 95% of the height. The individual slides have background images defined in them. If you are on a desktop computer, you can scroll through the carousel with your left and right arrows. If you are on a laptop or a mobile device, you swipe left and right.
It was at this point where I thought that I wanted to figure out something else, though. Having the images in the CSS gets a bit hard to deal with when they are going to likely be defined in something like vue or angular. Also, there isn’t a very good indicator of which slide you are on in the series. So, I went looking for ideas and came up with this.
The HTML looks roughly the same but the slides are now defined in the HTML instead of the CSS. The CSS provides a more pronounced horizontal scroll bar, though. As an added bonus, I am fairly sure that I can use hrefs to the IDs of the slides to link to individual slides in the carousel (something that might come in a future post).
Have a question, comment, etc? Feel free to drop a comment, below.