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?