May 17, 2015
The designs I’m working from included a carousel. I had some ideas of how I could make that work using CSS animations and the transform property, but that would leave me with a carousel that scrolled automatically and didn’t allow for user input which wasn’t really what I was looking for. After some thinking, I eneded up with a solution that uses absolute positioning and the :target pseudo-selector to change the z-index and opacity of our carousel items to cycle through them. It looks something like this:
This is the first item
Idque Caesaris facere voluntate liceret: sese habere. Qui ipsorum lingua Celtae, nostra Galli appellantur. Inmensae subtilitatis, obscuris et malesuada fames.
This is the second item
Vivamus sagittis lacus vel augue laoreet rutrum faucibus. Idque Caesaris facere voluntate liceret: sese habere. Cum sociis natoque penatibus et magnis dis parturient. Nihilne te nocturnum praesidium Palati, nihil urbis vigiliae.
And finally, the third
Quis aute iure reprehenderit in voluptate velit esse. Cum ceteris in veneratione tui montes, nascetur mus. Prima luce, cum quibus mons aliud consensu ab eo. Quam temere in vitiis, legem sancimus haerentia. Sed haec quis possit intrepidus aestimare tellus.
Let’s build one!
The structure of our carousel goes something like this: We have a main div.carousel-wrapper that gives our carousel its size. Inside our wrapper, we have span.hidden-target elements with unique IDs that act as targets for our carousel items controls, and div.carousel-item elements that hold the content of each of our carousel items.
Each of our div.carousel-item elements have some content within them, and two links, a.arrow-prev and a.arrow-next, which we use to cycle between the carousel items.
Because our individual carousel items will be position: absolute (so we can stack them on top of eachother), we have to set the div.carousel-wrapper’s height manually, and it makes sense to do this inline. We’re going to try to offload as much of our CSS to our external stylesheet, but some of the items we’ll have to write inline in order to make our carousel reusable and scalable.
I’m also using inline CSS to set the background image of two of our div.carousel-item elements to make them a little more vibrant, but we’ll leave that out below so that our markup is more readable.
That’s it for our HTML. It’s surprisingly light. The CSS (SCSS, in this case) is where the magic happens.
And that’s it! You have a carousel that’s fully functional and is 100% HTML and CSS! We only made a carousel with three items, but you can keep adding items, just make sure you add more target items, and you link up your arrow links correctly.
I hope you enjoyed this. Let me know your thoughts or what you would’ve done differently on Twitter at @ddggccaa.