by Nemrut Creative Studio on 11 Jun 2020
For this tutorial you can create a carousel / slider by following simple steps:
<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-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>
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;
}
That's it. You can style it with your own Tailwindcss configuration.
Copyright ©2021 Nemrut Creative Studio