Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › carousels

How to Add a Consistent Gap Between Carousel Slides with CSS

By Freedom251 Team · · 8 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The correct code depends on what creates your carousel. In Swiper, set the spaceBetween option when you initialize the slider. In a hand-built flex carousel, put a CSS gap on the flex container that directly lays out the slides. Do not add a universal slide selector until you have identified the library and the element that controls layout.

For Swiper, this is the smallest working change:

const swiper = new Swiper('.swiper', {
  spaceBetween: 16,
});

For a custom flex layout, the equivalent is:

.slides {
  display: flex;
  gap: 16px;
}

Choose the spacing method that matches your carousel

A “slide” is not positioned the same way in every carousel. A library may calculate each slide’s transform, width, and snap point in JavaScript. A custom component may simply place cards in a flex row and scroll that row. The visible gap must be configured at the layer that owns those calculations.

As an Amazon Associate I earn from qualifying purchases.

Carousel implementation Primary spacing control Where to apply it Important limitation
Swiper spaceBetween: 16 Swiper initialization options Swiper warns that slide margins used with spaceBetween can interfere with navigation.
Custom flex carousel gap: 16px The flex container that directly lays out the slides The selector must match the actual wrapper in your rendered markup.
Another slider library or site-builder carousel Library-specific spacing setting The component’s documented option or editor control The correct property and default are not stated without identifying the implementation.

The number 16 is an example in pixels. Replace it with the distance your design needs, then verify the result at each responsive breakpoint and while the carousel is moving.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Swiper: use spaceBetween, not slide margins

Swiper documents spaceBetween as the “Distance between slides in px.” Its default is zero, so slides touch unless you provide a value. The option accepts a number or string. The official API reference is available at Swiper’s API documentation.

#1 Best Overall
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

Basic Swiper configuration

const swiper = new Swiper('.swiper', {
  spaceBetween: 16,
});

This asks Swiper to calculate a 16-pixel distance between adjacent slides. Keep the setting inside the object passed to new Swiper(); adding a CSS rule to an unrelated wrapper will not change Swiper’s internal slide positions.

Complete markup example

<div class="swiper product-carousel">
  <div class="swiper-wrapper">
    <div class="swiper-slide">First slide</div>
    <div class="swiper-slide">Second slide</div>
    <div class="swiper-slide">Third slide</div>
  </div>
  <button class="swiper-button-prev" type="button" aria-label="Previous slide"></button>
  <button class="swiper-button-next" type="button" aria-label="Next slide"></button>
</div>

<script>
  const swiper = new Swiper('.product-carousel', {
    spaceBetween: 16,
    navigation: {
      nextEl: '.swiper-button-next',
      prevEl: '.swiper-button-prev',
    },
  });
</script>

The extra markup is only to show where the option belongs. Your existing Swiper HTML and navigation configuration can remain unchanged; add or adjust spaceBetween in the same initialization object.

Responsive Swiper spacing

If the design needs different distances at different viewport widths, use Swiper’s breakpoint options rather than trying to override slide margins:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const swiper = new Swiper('.product-carousel', {
  spaceBetween: 12,
  breakpoints: {
    768: {
      spaceBetween: 20,
    },
    1200: {
      spaceBetween: 24,
    },
  },
});

In this example, the base value is 12 pixels and larger breakpoints request 20 and 24 pixels. Use values that fit the number of slides visible at each width. A gap that works for three narrow cards may leave too little room when only one large card is shown.

Why not add margin-right to .swiper-slide?

Swiper specifically cautions that applying CSS margins to slide elements while using spaceBetween may prevent navigation from working properly. Swiper calculates positions from its own slide measurements; a second spacing system can make the visual distance and the calculated snap distance disagree.

Use one approach for a Swiper instance. Prefer spaceBetween when Swiper owns the layout. If an existing project already uses slide margins and you cannot change the initialization, test every navigation path, loop mode, and responsive breakpoint before keeping that arrangement. Do not assume that a margin which looks correct on the first slide is safe for all positions.

Custom flex carousel: put gap on the layout wrapper

For a hand-built carousel, the slides are commonly direct children of a flex container. In that case, gap belongs on the container, not on every card. The container creates consistent space between its flex items without requiring a special rule for the last slide.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
.carousel-viewport {
  overflow: hidden;
}

.slides {
  display: flex;
  gap: 16px;
  transform: translateX(0);
  transition: transform 300ms ease;
}

.slide {
  flex: 0 0 280px;
}
<div class="carousel-viewport">
  <div class="slides">
    <article class="slide">First slide</article>
    <article class="slide">Second slide</article>
    <article class="slide">Third slide</article>
  </div>
</div>

Here, .slides is the element that directly lays out the .slide items, so it receives display: flex and gap. The viewport clips the row while the script changes the row’s transform. If your markup uses different class names, substitute the selector for your actual layout wrapper.

Make the movement account for the gap

A custom carousel usually advances by a calculated distance. If each slide is 280 pixels wide and the gap is 16 pixels, moving exactly 280 pixels will leave the next slide 16 pixels too far to the side. Advance by the slide width plus the gap, or measure the rendered distance instead of hard-coding only the card width.

const track = document.querySelector('.slides');
const firstSlide = track.querySelector('.slide');
const gap = parseFloat(getComputedStyle(track).columnGap) || 0;
const step = firstSlide.getBoundingClientRect().width + gap;

function showSlide(index) {
  track.style.transform = `translateX(-${index * step}px)`;
}

This example reads the horizontal gap from the track and adds it to the first slide’s rendered width. It assumes the slides have a uniform width and that the track uses a horizontal flex direction. If slides have different widths, measure the target slide’s offset from the track instead of using one constant step.

Use logical spacing when direction can change

gap works in both left-to-right and right-to-left layouts without changing which side receives a margin. That makes it safer for a component that may switch writing direction. Keep the visual order and keyboard behavior aligned with the direction configured by your carousel script.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When the gap does not appear

A missing gap usually means the rule is applied to the wrong element, another rule overrides it, or the movement calculation does not include the new distance. Check the rendered page rather than guessing from source markup.

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

1. Confirm the element that owns layout

  1. Open developer tools and inspect a visible slide.
  2. Move up the DOM tree until you find the element whose computed style includes display: flex.
  3. Confirm that the slide elements are direct children of that element. Apply gap to this parent.
  4. In the computed styles panel, verify that gap or column-gap has the intended pixel value.

If a nested wrapper is the flex container, adding gap to the outer carousel shell will not space the slides. Likewise, a selector such as .slides does nothing if your page actually uses .swiper-wrapper or a generated site-builder class.

2. Check whether the rule is being overridden

Look for a later declaration such as gap: 0, a more specific selector, or an inline style. Temporarily add a clearly visible test value in developer tools, such as gap: 40px. If the layout changes, the selector works and the issue is cascade order or the chosen value. Fix the CSS organization instead of leaving an unexplained !important.

3. Distinguish clipping from no spacing

An overflow: hidden viewport can conceal the next slide and make a gap appear absent. Temporarily disable clipping or inspect the track’s box edges. The gap should exist between adjacent slide boxes even when part of the row is outside the viewport.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

4. Check fixed widths and shrinking

Flex items can shrink to preserve the row’s available width. If the slides are supposed to remain card-sized, use an explicit basis such as flex: 0 0 280px. If your script sets a width on each slide, ensure that width is not being recalculated after the gap is added. A layout that shrinks the cards may look as though the gap was ignored when the real change is reduced slide width.

5. Recalculate after resize

If the carousel measures slide positions on startup, changing the gap through a responsive rule can make the stored step stale. Re-run the component’s update or measurement routine after a resize, or calculate the current width and gap when the user moves between slides. This is especially important when the number of visible slides changes at a breakpoint.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Spacing controls in other carousel libraries

Do not copy Swiper’s spaceBetween option into another library unless that library documents the same property. Some components expose a “slide spacing,” “item gap,” or “ gutter” field; others expect a CSS variable or a class on the track. The title alone does not identify the implementation, so there is no universal selector or option that can be guaranteed to work.

Find the component’s initialization code or editor settings first. Search for the element that contains all slide items, then determine whether the library calculates positions from an option. If it does, use that documented option. If it only renders a normal flex row, use gap on the row’s layout container. Keep the navigation test in your verification routine after making the change.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Accessibility and interaction checks after changing spacing

Spacing is visual, but a carousel change can expose interaction bugs if movement math is tied to slide dimensions. After adding a gap, check the following states:

  • Keyboard focus moves to the expected slide and is not trapped between the viewport edge and the next card.
  • Previous and next buttons stop or wrap at the same logical slide positions as before.
  • At the first and last positions, no unintended horizontal scrollbar appears outside the intended viewport.
  • Touch or pointer dragging lands on a complete slide rather than stopping inside the gap.
  • At every responsive breakpoint, the visible slide count and the distance advanced by one control press remain consistent.
  • Users who prefer reduced motion still receive a usable transition if your component offers a reduced-motion rule.

For Swiper, test navigation after changing spaceBetween because the documented margin warning is specifically about navigation behavior. For a custom track, test the calculation that converts an index into a transform; visual spacing alone does not prove that snapping is correct.

A practical implementation checklist

  1. Identify the carousel engine: Swiper, a custom flex row, or another component.
  2. Locate the element that directly lays out the slide items.
  3. For Swiper, add spaceBetween to the initialization object and remove competing slide margins.
  4. For a custom flex row, add display: flex and gap to the layout wrapper.
  5. Set slide widths or flex bases so cards do not shrink unexpectedly.
  6. Update custom movement calculations to include the gap.
  7. Check computed styles, overflow, and responsive rules in developer tools.
  8. Test arrows, dragging, keyboard focus, looping if enabled, and the first and last positions.

Using the spacing control owned by the carousel is the safest path: Swiper’s documented option for Swiper, and CSS gap on the actual flex track for a custom implementation. This keeps the visual distance and the component’s navigation math aligned.

Quick Recap

SaleBestseller No. 1
HTML and CSS: Design and Build Websites
HTML and CSS: Design and Build Websites
HTML CSS Design and Build Web Sites; Comes with secure packaging; It can be a gift option
$14.94
SaleBestseller No. 3
SaleBestseller No. 4
Web Design with HTML, CSS, JavaScript and jQuery Set
Web Design with HTML, CSS, JavaScript and jQuery Set
Brand: Wiley; Set of 2 Volumes
$35.05

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

carouselsCSSJavaScriptSwiperWeb development

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.