Animate a carousel!

The target is to add and animate a carousel using css.

Ok, so some base rules. We know bootstrap has a carousel. The carousel adds an .active class on an item when scolled to. The timeout of a default carousel is 5000 ms. For the images we use unsplash because they are awesome. Lets go.


The example

So lets see what we are making.

The carousel slides, on every slide the title animates down. After that the buttons animate in.

A slide

For a slide i use an responsive embed so i can force it to an 16×9 frame.

Then we just add a title and some buttons.

Ad expedita impedit


<div class="embed-responsive embed-responsive-16by9">
    <div class="embed-responsive-item" style="background-image: url(https://images.unsplash.com/photo-1455717974081-0436a066bb96?dpr=1&auto=compress,format&fit=crop&w=800&h=450&q=80);">
        <h3>Ad expedita impedit</h3>
        <div class="row py-3">
            <div class="col-2"></div>
            <div class="col-4">
                <a href="#" class="btn btn-primary btn-block">
                    <i class="fa fa-puzzle-piece"></i>
                    Button 1
                </a>
            </div>
            <div class="col-4">
                <a href="#" class="btn btn-info btn-block">
                    <i class="fa fa-paper-plane"></i>
                    Button 2
                </a>
            </div>
            <div class="col-2"></div>
        </div>
    </div>
</div>

Some animations

So next we will need some animations. We will animate them on the .carousel-item.active class so we can use the active carousel item as a base.

So in this example i fade in and slide down the title on the h3 elemen.

.carousel-item.active h3 {
  animation: animate-carousel-title 1s normal forwards;
}

@keyframes animate-carousel-title {
  0% {
    transform: translate(0, -2em);
    opacity: 0;
  }
  100% {
    transform: translate(0, 0);
    opacity: 1;
  }
}

And the buttons

Next we animate the buttons.

Note, we also add an animation-delay on the items, so they start after each other.

.carousel-item.active .btn-primary {
  animation: animate-carousel-btn-primary 1s normal forwards;
  animation-delay: 1s;
}

.carousel-item.active .btn-info {
  animation: animate-carousel-btn-info 1s normal forwards;
  animation-delay: 2s;
}

@keyframes animate-carousel-btn-primary {
  0% {
    opacity: 0;
    transform: translate(-3em, 0);
  }
  100% {
    opacity: 1;
    transform: translate(0, 0);
  }
}

@keyframes animate-carousel-btn-info {
  0% {
    opacity: 0;
    transform: translate(3em, 0);
  }
  100% {
    opacity: 1;
    transform: translate(0, 0);
  }
}

And done.

So what we end up with is a carousel and on every slide the animation starts over.

You can check out the example on the page for the final result.

You can of course create the most elaborate animation you can think of. Just go wild.