Expert tips for adding spacing between images in carousel sliders and eliminating glitches during slides

After creating a carousel following the guidance of this source and initially sharing it on this platform, I encountered an issue with the padding on the first image. As a solution, I removed the padding from the first image, but this caused the image to be excessively wide.

To address this, I decided to remove the padding from all the images and introduce a margin-left to create a gap.

.carousel-item img {
    padding: 0;
    margin-right: 1rem; /* for gap */
}

However, this adjustment resulted in a glitch when I tried to slide through the carousel.

Is there a way to add spacing between images (excluding the first and last images) without encountering this glitch?

Here is the Codepen Link: https://codepen.io/Nisharg/pen/qwajmx

$('#travelCarousel').carousel({
    interval: false
});

$('#travelCarousel.carousel .carousel-item').each(function(){
    let next = $(this).next();
    if (!next.length) {
        next = $(this).siblings(':first');
    }
    next.children(':first-child').clone().appendTo($(this));

    for (let i=0;i<3;i++) {
        next=next.next();
        if (!next.length) {
            next = $(this).siblings(':first');
        }

        next.children(':first-child').clone().appendTo($(this));
    }
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css"> 
<style>
.carousel-item img {
  padding: 0;
  margin-right: 1rem; /* for gap */
}


  .carousel-inner .carousel-item.active,
  .carousel-inner .carousel-item-next,
  .carousel-inner .carousel-item-prev {
      display: flex;
  }

  .carousel-inner .carousel-item-right.active,
  .carousel-inner .carousel-item-next {
      transform: translateX(33.33333333%);
  }

  .carousel-inner .carousel-item-left.active,
  .carousel-inner .carousel-item-prev {
      transform: translateX(-33.33333333%);
  }

  .carousel-inner .carousel-item-right,
  .carousel-inner .carousel-item-left {
      transform: translateX(0);

  }
</style>
<div class="travel__carousel">
<div id="travelCarousel" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img class="col-md-6 col-xl-4" src="https://picsum.photos/200/300?image=0" alt="img-1">
</div>
<div class="carousel-item">
<img class="col-md-6 col-xl-4" src="https://picsum.photos/200/300?image=2" alt="img-2">
</div>
<div class="carousel-item">
<img class="col-md-6 col-xl-4" src="https://picsum.photos/200/300?image=3" alt="img-3">
</div>
<div class="carousel-item">
<img class="col-md-6 col-xl-4" src="https://picsum.photos/200/300?image=4" alt="img-4">
</div>
<div class="carousel-item">
<img class="col-md-6 col-xl-4" src="https://picsum.photos/200/300?image=5" alt="img-5">
</div>
</div>
</div>
<div class="travel__arrows">
<a class="btn" href="#travelCarousel" role="button" data-slide="prev"><i class="fas fa-arrow-left"></i></a>
<a class="btn" href="#travelCarousel" role="button" data-slide="next"><i class="fas fa-arrow-right"></i></a>
</div>
</div>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>

I am seeking a solution that does not involve using any third-party JS libraries like Slick.js.

Answer №1

One significant issue I see with this method is the inflexible "33.333%" transition value that doesn't consider the gap or margin. Using calc(x% + gap) as the transition value would provide a more effective solution.

Furthermore, to account for various bootstrap breakpoints that alter the number of visible slides, it's necessary to incorporate different transition offsets (e.g. 20% offset for smaller screens and 50% offset for larger screens). An example of this approach can be explored in this codepen.

Answer №2

The issue at hand is caused by the transparency of the gaps, allowing the next/previous sliding item to show through. One solution is to eliminate the transparency by making the gaps opaque.

An easy fix is to apply a white box-shadow to your image to fill the transparent gap:

.carousel-item img {
    padding: 0;
    margin-right: 1rem;
    /*added this*/
    box-shadow: 
       1rem 0 #fff,
      -1rem 0 0 #fff; 
}

$('#travelCarousel').carousel({
    interval: false
});

$('#travelCarousel.carousel .carousel-item').each(function(){
    let next = $(this).next();
    if (!next.length) {
        next = $(this).siblings(':first');
    }
    next.children(':first-child').clone().appendTo($(this));

    for (let i=0;i<3;i++) {
        next=next.next();
        if (!next.length) {
            next = $(this).siblings(':first');
        }

        next.children(':first-child').clone().appendTo($(this));
    }
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css"> 
<style>
.carousel-item img {
  padding: 0;
  margin-right: 1rem; /* for gap */
  box-shadow:
     1rem 0 0 #fff,
    -1rem 0 0 #fff;
}


  .carousel-inner .carousel-item.active,
  .carousel-inner .carousel-item-next,
  .carousel-inner .carousel-item-prev {
      display: flex;
  }

  .carousel-inner .carousel-item-right.active,
  .carousel-inner .carousel-item-next {
      transform: translateX(33.33333333%);
  }

  .carousel-inner .carousel-item-left.active,
  .carousel-inner .carousel-item-prev {
      transform: translateX(-33.33333333%);
  }

  .carousel-inner .carousel-item-right,
  .carousel-inner .carousel-item-left {
      transform: translateX(0);

  }
</style>

<div class="travel__carousel">
<div id="travelCarousel" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img class="col-md-6 col-xl-4" src="https://picsum.photos/200/300?image=0" alt="img-1">
</div>
<div class="carousel-item">
<img class="col-md-6 col-xl-4" src="https://picsum.photos/200/300?image=2" alt="img-2">
</div>
<div class="carousel-item">
<img class="col-md-6 col-xl-4" src="https://picsum.photos/200/300?image=3" alt="img-3">
</div>
<div class="carousel-item">
<img class="col-md-6 col-xl-4" src="https://picsum.photos/200/300?image=4" alt="img-4">
</div>
<div class="carousel-item">
<img class="col-md-6 col-xl-4" src="https://picsum.photos/200/300?image=5" alt="img-5">
</div>
</div>
</div>
<div class="travel__arrows">
<a class="btn" href="#travelCarousel" role="button" data-slide="prev"><i class="fas fa-arrow-left"></i></a>
<a class="btn" href="#travelCarousel" role="button" data-slide="next"><i class="fas fa-arrow-right"></i></a>
</div>
</div>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Integrating dual Google Maps onto a single HTML page

I'm facing an issue with implementing two Google maps on a single page where the second map seems to be malfunctioning. Below is the code I am currently using: <style> #map-london { width: 500px; height: 400px; } #map-belgium { wi ...

Ways to deactivate the hover effect on a bootstrap icon

I have incorporated this particular icon definition: <svg class="bi bi-arrow-repeat arrow-success" id="id-topdashboard-icon-refresh" width="28" height="28" viewBox="0 0 20 20" fill="currentColor&quo ...

Utilizing jQuery: How to pass the $this object along with additional parameters to a

Is there a way to pass the value of this along with other parameters to a function? I have attempted the following methods, but they have not been successful: function update_alt($this, my_param){ this_alt = $(this).attr('alt'); ...

Tips on prefixing Bootstrap 4 classes to prevent conflicts with CSS classes

Recently, I've been focusing on creating small applications for websites. The websites hosting these apps may or may not use a css framework. To prevent any potential conflicts, I have decided to add a unique prefix to all Bootstrap classes. For insta ...

changing pictures with jquery

Struggling with this code snippet: $('#clicked_package').css({"background-image" : "url(img/head_2.png)"}).fadeOut("slow"); $('#clicked_package').css({"background-image" : "url(img/head_2_normal.png)"}).fadeIn("slow"); No matter which ...

Pagination in the jQuery datatables plugin is not functioning as expected

Help Needed I am using the datatables jQuery Plugin to display a table, but I am facing an issue where all entries are shown without any pagination. Can someone please assist me with this problem? Below is my index.cshtml code: @{ Layout = null; } & ...

Tips for utilizing onsubmit following an ajax validation check

How can I implement the onsubmit method after an ajax check? The current onsubmit function is not working. $(document).ready(function(){ $("#p_code").change(function(){ $("#message").html("<img src='ajax_loader.gif' width='26 ...

Using a batch file to send an email

I have a goal to create an autorun file that can be placed on an external drive, flash disk, or CD. When executed, this file will run a series of commands that eventually send the computer's IP information back to me. Here is what I have so far... Th ...

Tips for submitting an e-mail through an HTML form with the help of Node.js and Gulp

Today, I've been tackling the challenge of creating an HTML contact form that can send an email using Node.js and Gulp. However, I'm struggling to find a solution. Using a relative path to a simple .PHP file doesn't seem to be working, so it ...

Stop capturing mouse and keyboard events within a specific div element on all web browsers

I manage a website with forms that have jquery autosave features and are updated using ajax. These forms include various types of input elements such as textboxes, jQuery UI datepickers, and time pickers... <div id="content"> <form id="line1"&g ...

What are the steps to implement character movement in a 2D game using JavaScript?

I'm having trouble getting the image with the ID "yoshi" to move around in my 2D game document.onkeydown = (e) => { if (e.keyCode == 37) yoshi.style.left = yoshi.offsetLeft - 5 + "px"; else if (e.keyCode == 38) yoshi.style.top = yoshi.offset ...

Error encountered while using the jquery with Twitter Search API

Looking to initiate a twitter search using the jquery and the twitter api, I consulted the documentation before writing this code: $.getJSON("http://search.twitter.com/search.json?callback=myFunction&q=stackoverflow"); function myFunction(r) { co ...

Issue with JSON or Jquery: Uncaught error message: Cannot access property 'error' as it is null

I am attempting to initiate an ajax call using the jQuery code provided below. However, when I try this in Chrome, I encounter an error that says 'uncaught typeerror cannot read property 'error' of null'. This prevents the preloader fr ...

How can you use CSS animations to animate two images in a way that hides one while showing the other?

click here for the image link visit this webpage for the link I need I am looking to add an animated section to my website. The inspiration comes from the webpage linked above, where images slide down one after another in a seamless manner. I attempted t ...

When the function $(document).width() is called, it may yield varying results depending on the timing of the call

Every time I use $(document).width(); within $(window).load(function(){}) or $(document).ready(function(){}), the result differs from when it is called inside $(window).resize(function(){}). The discrepancy is approximately 100px, and it's not due to ...

The URL "http://packagist.org/p/provider-3.json" was unable to be retrieved due to a bad request error (HTTP/1.1 400 Bad Request)

Encountering a 400 bad request issue when trying to connect over HTTP, despite the package only being installable via HTTP. Attempting to override in composer.json to force HTTPS as suggested by others for a workaround, but that solution doesn't seem ...

Connecting an image to its corresponding content through hover effect

Can someone please assist me? I am trying to create a hover effect on an image with an "add to cart" link similar to what is shown here: I seem to be having trouble with the code, could you provide some guidance? .hunderter { background: url(http ...

Trouble with flex wrap in my design template using Material UI

How can I create a responsive template using flexbox wrapping method? <Box sx={{ padding: 0, margin: 0, listStyle: "none", display: "flex", flexFlow: ...

Limit text to two lines inside a cell in a table

Apologies for not providing any evidence of my own efforts. I'm looking to wrap text in a table cell, but limit it to just 2 lines. Expanding the width is not possible. Any suggestions on how to achieve this? ...

Triggering an event on a checkbox following an AJAX response

My website has 3 different categories, each with a dropdown menu containing various values with checkboxes. When a checkbox is checked, an AJAX request is triggered to fetch a response. The problem I'm facing is that the dropdown menus disappear afte ...