How to create carousel / slider using Alpine JS + Tailwindcss

by Nemrut Creative Studio on 11 Jun 2020

For this tutorial you can create a carousel / slider by following simple steps:

Write some markup

<div x-data="{items: ['foo','bar','baz','buz'], active: 0}">
    <div class="snap overflow-auto relative flex-no-wrap flex transition-all" x-ref="slider"
        x-on:scroll.debounce="active = Math.round($event.target.scrollLeft / ($event.target.scrollWidth / items.length))">
        <template x-for="(item,index) in items" :key="index">
            <div class="w-full flex-shrink-0 h-32 bg-black text-white flex items-center justify-center">
                <span x-text="item"></span>
            </div>
        </template>
    </div>
    <div class="p-4 flex items-center justify-center flex-1 bg-black bg-opacity-75">
        <button
            class="outline-none focus:outline-none rounded-full mx-4 text-white"
            x-on:click=" $refs.slider.scrollLeft = $refs.slider.scrollLeft - ($refs.slider.scrollWidth / items.length)">
            <
        </button>
        <template x-for="(item,index) in items" :key="index">
            <span class="bg-white w-3 h-3 block mx-1 bg-white bg-opacity-25 shadow rounded-full"
            x-bind:class="{'bg-opacity-100': active === index }"></span>
        </template>
        <button
            class="outline-none focus:outline-none rounded-full mx-4 text-white"
            x-on:click="$refs.slider.scrollLeft = $refs.slider.scrollLeft + ($refs.slider.scrollWidth / items.length)">
            >
        </button>
    </div>
</div>

Write some css

Some of the required css does not come with the Tailwindcss such as scroll-snap-type, so we need to add them as:

.snap {
  -ms-scroll-snap-type: x mandatory;
  scroll-snap-type: x mandatory;
  -ms-overflow-style: none;
  scroll-behavior: smooth
}
.snap::-webkit-scrollbar {
  display: none;
}

.snap > div {
  scroll-snap-align: center;
}

Result

That's it. You might want to style it as your own Tailwindcss.

Copyright ©2020 Nemrut Creative Studio