Building Carousels and sliders with TailwindCSS

Carousels are a popular component in web design that allows you to showcase multiple images or content in a slideshow format. With Tailwind CSS, a utility-first CSS framework, you can easily create dynamic and responsive carousels for your website. In this tutorial, we'll walk through the process of building a carousel using Tailwind CSS and vanilla JavaScript.

I tried to use the carousel provided by the Flowbite component library, but the carousel on Flowbite needed that height for the carousel or slider be specified and I didn't like this idea. Therefore i took the opportunity to build my own carousel and slider that was height responsive. More opportunity for me to master Tailwindcss 

Prerequisites

Before getting started, make sure you have the following prerequisites:

  • Basic understanding of HTML, CSS, and JavaScript.
  • Familiarity with Tailwind CSS.

Step 1: Setting Up the Project

To begin, create a new HTML file and include the necessary CSS and JavaScript files. You can either use a local copy of Tailwind CSS or link to the CDN:





Make sure to replace path/to/your/script.js with the correct path to your JavaScript file.

Step 2: HTML Structure and styling the carousel

Next, let's define the HTML structure for our carousel. We'll use a

element with a grid layout to display the slides in a row. Each slide will be contained within a
element with the w-full class for full-width display. Replace the placeholder content with your actual slide content.


Read also : How to increase your reach,engagement and visibility on Instagram.


The code above is an example of HTML markup that sets up a carousel using a container element with specific classes and attributes. Let's break it down:

1. The outermost `

` element has the class "relative" and the attribute `data-slide-motion="slide"`. The class "relative" is used for positioning context, and the `data-slide-motion` attribute with the value "slide" indicates that this container will have a sliding motion for the slides by default when the page loads.

2. Inside the outer `

`, there is another `
` element with multiple classes:

   - "slides-container": This class represents the container for the slides.
   - "mb-14": This class adds a margin-bottom of 14 units of spacing to the container.
   - "grid": This class sets the display property of the container to grid.
   - "touch-manipulation": This class enables touch manipulation for the container, allowing touch-based scrolling.
   - "snap-x": This class enables horizontal snapping for the container.
   - "snap-mandatory": This class ensures that snapping behavior is mandatory, meaning the container will always snap to a slide.
   - "grid-flow-col": This class sets the flow direction of the grid container to column.
   - "gap-0": This class sets the gap between grid items to 0.
   - "overflow-auto": This class allows the container to have a scrollable overflow when the slides exceed the container's width.
   - "overflow-y-hidden": This class hides the vertical scrollbar of the container.
   - "scroll-smooth": This class adds smooth scrolling behavior to the container.

   Additionally, the `style` attribute is used to set inline styles for the container. In this case, it sets `grid-auto-columns` to `100% !important`, ensuring that each slide takes up the full width of the container.


Read also : Top 3 skills a UX Designer should have.


3. Inside the slides container, there are multiple `

` elements, each representing a slide. These slides have the classes "w-full" (occupies the full width of the container) and "p-6" (adds padding of 6 units of spacing to the slide).

4. The slide content should be placed inside each slide `

`. In the example you provided, the slide content is left empty (``), but you can add any desired content such as images, text, or other HTML elements within each slide.

5. The slide controls, controls which direction the elements in the carousel moves.

To summarize, the provided HTML code above sets up a slideshow or carousel by creating a container element with specific classes and attributes. The container enables touch-based scrolling, horizontal snapping, and smooth scrolling behavior. Multiple slide elements are placed inside the container, and each slide takes up the full width of the container. The slide content should be added within each slide element.

Step 3: Adding Carousel Functionality

Now, let's add the JavaScript code to make our carousel functional. Create a new JavaScript file and link it to your HTML file as mentioned in Step 1.


Read also : Password Strength Indicator using REGEX.


//Get all slideContainers
  const slideContainers = document.querySelectorAll("[data-slide-container]");
  const slideDistance = window.screen.availWidth / 1.5;
  // Iterate over each container, incase there are more than one carousels in a page
  slideContainers.forEach((container) => {
    let containerMotion =
      container.parentElement.attributes["data-slide-motion"].value;
    //Implement automatic slide
    if (containerMotion == "slide") {
      setInterval(function () {
        container.scrollLeft += slideDistance;
      }, 5000);
    }
    let nextButton = container.querySelectorAll("[data-slide-next]")[0];
    let previousButton = container.querySelectorAll("[data-slide-previous]")[0];

    //add a click event to each of the slide
    nextButton.addEventListener("click", () => {
      container.scrollLeft += slideDistance;
    });

    previousButton.addEventListener("click", () => {
      container.scrollLeft -= slideDistance;
    });
  
  });

The code above implements a carousel or slideshow functionality on a web page. Let's break down the code step by step:

1. The first line of code selects all elements with the attribute `data-slide-container` using the `querySelectorAll` method and stores them in the `slideContainers` variable. These elements represent the containers that hold the slides.

2. The next line calculates the `slideDistance` by dividing the available width of the window (`window.screen.availWidth`) by 1.5. This value determines the distance to scroll the container when navigating between slides.

3. The code then iterates over each slide container using the `forEach` method.

4. Inside the loop, it retrieves the value of the `data-slide-motion` attribute from the container's parent element and stores it in the `containerMotion` variable.


Read also : Development bank of Nigeria (DBN) loan worth at least ₦10million.


5. If the `containerMotion` is set to `"slide"`, the code sets an interval using `setInterval` that triggers a function every 5000 milliseconds (5 seconds). This function increments the `scrollLeft` property of the container by the `slideDistance`, causing the container to scroll horizontally.

6. The code then selects the next and previous buttons within the container using the `[data-slide-next]` and `[data-slide-previous]` attribute selectors, respectively, and assigns them to the `nextButton` and `previousButton` variables.

7. Event listeners are added to both the next and previous buttons. When the next button is clicked, the container scrolls to the right by `slideDistance` pixels. Similarly, when the previous button is clicked, the container scrolls to the left by `slideDistance` pixels.

Overall, this code sets up a slideshow/carousel behavior for elements on a web page. The automatic slide functionality scrolls the container at a regular interval, and the next/previous buttons allow manual navigation through the slides.

Turn a carousel to a slider

We can use the same HTML and JavaScript code, but we have to edit the HTML:


Read also : Toggle password visibility with JavaScript.



Overall, the main differences between the two code snippets are the values of the data-slide-motion attribute and the classes used for the slides in the container. These differences  affect the behavior and styling of the slideshow or carousel. The first snippet has a sliding motion, while the second snippet has a static motion (no automatic sliding). The second snippet also uses different snap behaviors  snap-center for the slides within the container. I also removed style="grid-auto-columns: 100% !important;"   which ensure  that each slide does not take up the full width of the container.

We now end up with something like the image below for a slider (the first element in the picture is the slider).

Carousel and slide with tailwindcss

Conclusion

Congratulations! You have successfully built a carousel using Tailwind CSS. Carousels are versatile components that can enhance the user experience and showcase your content in an interactive way. With Tailwind CSS, you can quickly style and customize carousels to fit your project requirements.

Remember to experiment with different designs, animations, and features to create unique and engaging carousels for your website. Happy coding!


Read also : Apply middleware to route groups in NuxtJs in Nuxt config.