DEV Community

Cover image for Creating a Single Image Slider using Swiper.js
Rafa Rafael
Rafa Rafael

Posted on

Creating a Single Image Slider using Swiper.js

Swiper.js is a powerful library for creating touch sliders and carousels for mobile and desktop websites.

One interesting use case is creating a slider with only one image, where each slide shows a different section of a larger image. This can be useful for showcasing various parts of a product, a process, or a story. Here's how you can achieve this:

Step 1: Crop the Image
Start by cropping the image into sections that have a consistent width and height. E.g. You can use an image editing tool to crop the image into sections, e.g. With dimensions of 268 × 840 pixels each.

Step 2: Adjust the Slider Configuration
Next, adjust the Swiper configuration to fit your cropped images. Here's an example of how you might configure the slider:

<div class="swiper my-slider" data-slides-per-view="2.5" data-allow-touch-move="1" data-centered-slides="1" data-autoplay="0" data-centered-slides-bounds="1">
    <div class="swiper-wrapper">
        @for ($i = 0; $i <= 6; $i++)
        <img src="{{ asset("cropped-images/ci-{$i}.png") }}" alt="Purchasing Process" class="w-full swiper-slide">
        @endfor
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

In this example, I used slides per view (data-slides-per-view="2.5") to adjust the slide's width of the cropped sections' image. In the swiper.js properties, I also set space between to 0 so there will be no gaps between the cropped image, and looked like one image.

You can configure your settings based on your specific design needs. For example, in the sandbox demo I created, I used a different of configurations. You can check the example here.

Troubleshooting
At the time of writing, the most recent version swiper.js is version 11. If you are using an older version, you may encounter issues with the width of your images. To resolve this, you can adjust the .swiper-slide class to ensure that the cropped images fit well within the slider while still looked as a single image. Just override the .swiper-slide class and set it as follows:

.swiper-slide {
   flex-shrink: 1 !important;
}
Enter fullscreen mode Exit fullscreen mode

Then play around the slides per view value to get your desired results.

Creating a Swiper.js slider with cropped images can be a creative way to showcase content on your website. By carefully cropping your images and adjusting the Swiper configuration and styles, you can create a visually appealing slider that engages your users.

Enjoy!

Top comments (0)