Bootstrap 4 Custom Carousel
Making a Responsive Multi-item Slider
I’ve seen many variations of the Bootstrap Carousel, but for my purposes I needed a slider that met the following requirements:
Display multiple slides horizontally
Slide only one-at-a-time
Display a single slide on mobile
The Basic Bootstrap 4 Carousel
The default, out-of the-box slider, is designed to show a single slide at a time…
<div class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img class="d-block w-100" src="..." alt="First slide">
</div>
<div class="carousel-item">
<img class="d-block w-100" src="..." alt="Second slide">
</div>
<div class="carousel-item">
<img class="d-block w-100" src="..." alt="Third slide">
</div>
</div>
</div>
By using the grid within each carousel-item
it’s easy to show multiple items per “slide”. For example, here is 3 items per slide using 2 carousel-items (a total of 6 slides)…
<div class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<div class="row">
<div class="col"><img src=".." alt="1 slide"></div>
<div class="col"><img src=".." alt="2 slide"></div>
<div class="col"><img src=".." alt="3 slide"></div>
</div>
<div class="row">
<div class="col"><img src=".." alt="4 slide"></div>
<div class="col"><img src=".." alt="5 slide"></div>
<div class="col"><img src=".." alt="6 slide"></div>
</div>
</div>
</div>
</div>
However, this didn’t work for my requirements, because it moves all 3 items when in moves to the next “slide”.
[1,2,3]… [4,5,6]…
In my case, I needed the carousel to move only a single slide at a time, but still show 3 slides at a time.
[1,2,3]… [2,3,4]… [3,4,5]…[4,5,6]…
For this, I found a helpful question on Stack Overflow. The accepted answer shows how to create a carousel that only advances a single slide at a time.
However, this still didn’t completely work for my requirements, because it wasn’t responsive, and the slides got squished across the screen on mobile. I unsuccessfully made more changes, that caused the items to stack vertically on mobile screens. Making it responsive is still a challenge.
So, I went back to the drawing board to find a Bootstrap 4 carousel that met my 3 requirements:
- shows multiple items
- advances only slider one at a time
- shows only a single item on smaller screens
After several iterations, I found this implementation that uses CSS selectors determine which item(s) to show and make “active”. This also required a little jQuery hook into the Bootstrap 4 carousel “slide” event.
And there it is! A responsive Bootstrap carousel that shows 4 items, slides one-at-a-time, and shows only a single slide on smaller screens.
❤ __ Tom Michew
There’s more to Learn on Bootstrap 4
Try these related articles…