SwiperJs: I'm struggling to align groups of 2 slides in the center because I am unable to limit the width of the slides

I am currently working on a project involving SwiperJS to create a slider that showcases two slides per group, neatly centered within the container of the slider. Despite my best efforts, I have encountered an issue where the slides expand to occupy the entire width of the container, which is not the desired outcome. Ideally, I would like the slides to only take up a portion of the container's width while remaining centered.

CodeSandbox Example:

If you want to see the problem live, please check out my CodeSandbox example here.

Attempted Solutions:

  • Experimented with flexbox properties such as flex, justify-content: center, and margin-inline: auto along with width: fit-content for the slides.
  • Tried limiting the swiper-container width.
  • Despite trying these approaches, none of them have resolved the issue, hinting that there might be a simpler solution that I'm overlooking.

Current Layout: https://i.sstatic.net/bZ2p13xU.png

Desired Layout: https://i.sstatic.net/IY3VSPGW.png

Note: While the prev-arrow is present in the screenshots, my main focus is on achieving the centering effect.

Relevant code:

Javascript

$.getScript(
      "https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js",
      function () {
        new Swiper(".customSwiper", {
          grabCursor: true,
          slidesPerView: 2,
          centeredSlides: false,
          spaceBetween: 10,
          loop: false,  
          slidesPerGroup: 2,  
          navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
          },
        });
      }
    );

CSS:

/* swiper */
.swiper-slide {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  max-width: unset !important;
}
.swiper-container {
  width: 100vw;
  height: 100%;
  overflow: hidden;
  position: relative;
  background: #FFF;
  max-width: unset !important;
}
/* card being displayed */
.card {
  border-radius: 25px;
  background: #F8F8F8;
  box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.05);
  padding: 12px;
  display: grid;
  grid-template-columns: 1fr 5fr;
  max-width: 30em;
  width: fit-content;
  column-gap: 24px;
  }

Question: What adjustments can I make to either my SwiperJS configuration or CSS to prevent the slides from stretching across the entire container width and instead keep them centered as intended? Are there specific CSS properties or Swiper settings that could help rectify this behavior?

Answer №1

When the cards are grouped in pairs, it is necessary to align the "odd" cards to the right and the "even" cards to the left. This can be achieved by using :nth-child(odd) and :nth-child(even) respectively as shown below:

.card {
  …
 /**
  * Remove:
  * margin: 0 auto;
  */
}
  
.swiper-slide:nth-child(odd) .card {
  margin-left: auto;
}

.swiper-slide:nth-child(even) .card {
  margin-right: auto;
}

document.addEventListener('DOMContentLoaded', function () {
  const newCards = [
    // Array containing details of new cards with testimonials
  ];

  newCards.forEach((card) => {
    // Dynamically creating HTML for each new card
  });

  // Initialize Swiper for the custom slider
});
html,
body {
  position: relative;
  height: 100%;
}
body {
  background: #eee;
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
}
swiper-slide {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  max-width: unset !important;
}
.main-slider .swiper-slide {
  // Styling for the main slider
}

.swiper {
  padding: 0 15% !important;
}

.swiper-wrapper {
  // Additional styling for the swiper wrapper
}
.card {
  // Styling for the individual cards
}

.swiper-slide:nth-child(odd) .card {
  margin-left: auto;
}

.swiper-slide:nth-child(even) .card {
  margin-right: auto;
}
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>
<body>
  <!-- Swiper -->
  <div class="swiper customSwiper main-slider">
    <div class="swiper-wrapper">
      <!-- Dynamic card creation will be inserted here -->
    </div>
    <div class="swiper-button-next"></div>
    <div class="swiper-button-prev"></div>
  </div>
</body>

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

What causes Jest to throw ReferenceErrors?

Question Does anyone know why I am encountering this error? ● Test suite failed to run ReferenceError: Cannot access 'mockResponseData' before initialization > 1 | const axios = require('axios'); ...

How can I update a property within an object in a sequential manner, similar to taking turns in a game, using React.js?

I am currently working on a ReactJs project where I am creating a game, but I have encountered an issue. I need to alternate turns between players and generate a random number between 1 and 10 for each player, storing this random number inside their respec ...

Error in Next.js Image Component: Missing SRC

Encountering an error with the next.js image component, specifically related to a missing "src" property. Error: Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {} Th ...

manipulating data using javascript

I have an array of objects like this: var arr = [{'name':'one','age':24},{'name':'two','age':21}] Then I assigned this array to another variable var newVar = arr. Next, I modified the value of a ...

Learn the technique of swapping out a portion of a string with a value from an input field in real-time

My webpage has a form on the left side where users can input text, and on the right is some static text. I want the text on the right to update automatically as the user types in the input field on the left. In my HTML code, it looks something like this - ...

Could someone recommend a Python function that can encode output specifically for use in JavaScript environments?

Looking to securely encode output for JavaScript contexts in Python 3.6+? This means ensuring that any input string is properly encoded so that replacing VALUE with it will prevent all XSS attacks on the webpage, containing the input within the boundaries ...

What is the best way to implement JQuery Ajax in order to invoke a PHP file on the server side, which will then execute returned javascripts?

I am currently working on a client website that requires a cross-domain JQuery Ajax call to a PHP file on my server. The purpose of this call is to query the database for various stored JavaScripts, which will then be returned to the client and executed on ...

Ways to eliminate the extra space in a dropdown menu

Is there a way to eliminate padding on the "dropdown-menu" <ul> tag when the list is empty, so that no space is displayed in place of the padding? I want to avoid using .dropdown{padding: 0} because it will remove necessary padding when the list is ...

Exploring jQuery's Array Iteration Feature

Is there a way to create Custom Lists with a User-Friendly approach? For example: var unitA = []; unitA[0] = "Unit A One"; unitA[1] = "Unit A Two"; unitA[2] = "Unit A Three"; var unitB = []; unitB[0] = "Unit B One"; unitB[1] = "Unit B Two"; unitB[2] = " ...

I possess a compilation of URL links and I am seeking to identify the specific HTML div that corresponds to each URL within a webpage

Could you please help me figure out which HTML div each URL belongs to on a webpage using Java? I have a list of URLs that need to be matched with their respective HTML divs. ...

Update the content of a div element with the data retrieved through an Ajax response

I am attempting to update the inner HTML of a div after a certain interval. I am receiving the correct response using Ajax, but I am struggling to replace the inner HTML of the selected element with the Ajax response. What could be wrong with my code? HTM ...

Using jQuery to implement tiered radio buttons styled with Bootstrap

I am currently in the process of learning jQuery, so please excuse my lack of knowledge in this area. I am working on a web form using Bootstrap that involves tiered radio buttons. When the user selects "Yes" for the first option, it should display the ne ...

The error message "buildParams: Exceeded maximum call stack size with Uncaught RangeError" was

I'm having trouble pinpointing the mistake. Can someone please assist me? Every time I submit the form, I encounter the following error in the console: Uncaught RangeError: Maximum call stack size exceeded at buildParams I've looked at variou ...

I struggle with managing a z-index in conjunction with an absolute position

Check out this codesandbox to see the issue where the 3 dots button is displayed over the menu. Click on the 3 dots to understand the problem. Below is the CSS code for the menu: .more-menu { position: absolute; top: 100%; z-index: 900; float: l ...

Shatter a connection into pieces across various lines

Looking for a solution to displaying a long link in its entirety without overflowing? Seeking advice on how to wrap the text instead of having it overflow? Let me know your thoughts! ...

Retrieve the text located within the span tag using Selenium

When I try to inspect the element using Google Chrome, I come across the following code: <div class="form-style-abc"> <fieldset> <legend><span class="number">*</span>Search Zone</legend> I am trying to retrieve ...

Methods for retrieving a file within a nodejs project from another file

Currently, my project has the following structure and I am facing an issue while trying to access db.js from CategoryController.js. https://i.sstatic.net/8Yhaw.png The code snippet I have used is as follows: var db = require('./../routes/db'); ...

Learn the step-by-step process of converting JSON functionality into HTML/text output using Golang

I need to modify the API responses to display as HTML or text, as the current script only outputs JSON format. func writeJSONResponse(w http.ResponseWriter, statusCode int, data interface{}) { w.Header().Set("Content-Type", "applicatio ...

Collapsed navbars in Bootstrap 5 fail to display properly in a two-column format

Looking to create a responsive Bootstrap 5 navbar that collapses at the md breakpoint and displays navlinks in two columns upon collapse. Currently facing an issue where the navbar remains expanded and the toggle button fails to work after hitting the br ...

Tips for creating a horizontal list within a collapsible card

When a user clicks on a button, I am dynamically populating a list of items. Despite using list-group-horizontal, I am unable to make it display horizontally. HTML code <div id="textarea_display" class="mt-2 "> <label&g ...