DEV Community

Cover image for Pure CSS Carousel
Ustariz Enzo
Ustariz Enzo

Posted on • Updated on

Pure CSS Carousel

Hey fellow creators,

You can easily do a carousel completely in CSS, let's learn how to do that now!

If you prefer to watch the video version, it's right here :

Here's the source code if you want to follow along with me.

1. The HTML structure.

Create a frame that'll wrap everything, meaning the carousel, that'll contain several elements.
You need to put the exact same text in the first and last paragraph.

<div class="frame">
      <div class="carousel">
        <p class="element">"Incredible"</p>
        <p class="element">"Perfect"</p>
        <p class="element">"Awesome"</p>
        <p class="element">"Punctual"</p>
        <p class="element">"Incredible"</p>
      </div>
</div>
Enter fullscreen mode Exit fullscreen mode

2. Style the frame.

Style the frame so that it sits in the center of the page, has a coloured background and white text:

.frame {
    position: relative;
    top: 100px;
    margin: 0 auto;
    width: 600px;
    height: 200px;
    border-radius: 2px;
    background: #373737;
    color: white;
    overflow: hidden
}
Enter fullscreen mode Exit fullscreen mode

3. Style the elements.

Each element needs to take the full width and height of the frame. In order to do that, you'll use line-height and make it the same size as the height of your frame, here it'll be 200px.

.element {
    text-align: center;
    font-size: 50px;
    line-height: 200px;
}
Enter fullscreen mode Exit fullscreen mode

Why use line-height? It'll put 100px above the text and 100px below it, so that it'll center the text in the middle of the container.

4. Animate the carousel.

.carousel {
    animation: carousel 8s ease-in-out infinite;
}
@keyframes carousel {
    0%, 20% {
        transform: translateY(0);
    }
    25%, 45% {
        transform: translateY(-200px)
    }
    50%, 70% {
        transform: translateY(-400px)
    }
    75%, 95% {
        transform: translateY(-600px)
    }
    100% {
        transform: translateY(-800px)
    }
}
Enter fullscreen mode Exit fullscreen mode

Use the height of the frame in your translateY() so that each element of the carousel will slide up and show the different texts and then go back to the original value (which is 0).

Indeed, you could add more features with JavaScript, but it's already a nice way to create a basic slider in pure CSS.

Come and take a look at my Youtube channel: https://www.youtube.com/c/TheWebSchool

See you soon!

Enzo.

Top comments (0)