SwiperJs:我正在显示 2 张幻灯片组,它们应该居中,但我什至无法实现限制幻灯片宽度

问题描述 投票:0回答:1

我正在使用 SwiperJS 创建一个滑块,每组显示两张幻灯片,位于滑块容器的中心。我当前的实现导致幻灯片扩展以填充容器的整个可用宽度,这不是我想要的。理想情况下,我希望幻灯片仅占据容器宽度的一部分,同时保持居中。

CodeSandbox 示例:

请参阅我的 CodeSandbox 示例此处,了解该问题的现场演示。

尝试的解决方案:

  • 我尝试使用 flex、justify-content: center 和 margin-inline: auto 以及 width: fit-content 来制作幻灯片。
  • 我试图限制滑动容器的宽度。
  • 这些方法都没有解决这个问题,这表明我可能遗漏了一些明显的东西。这应该更简单。

这是当前布局的样子: enter image description here

这是我想要实现的目标(所需的布局): enter image description here

注意上一个箭头不相关,我只是专注于实现居中。

相关代码:

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;
  }

问题: 如何调整我的 SwiperJS 配置或 CSS 以防止幻灯片拉伸以填充整个容器宽度,而是像我所说明的那样将它们居中?是否有特定的 CSS 属性或 Swiper 设置可以纠正此行为?

javascript html css slider swiper.js
1个回答
0
投票

由于卡片分成两部分,因此“奇数”卡片需要向右对齐,而“偶数”卡片则需要向左对齐。因此,我们可以分别使用

:nth-child(odd)
:nth-child(even)
来对齐它们:

.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 = [
    {
      profilePhotoSrc:
        'https://ik.imagekit.io/ei6mtk4ll/Stopwatts/SW-008/sw-008-card-1.png',
      testimonial:
        'I’m so surprised by the amount we saved with these ESaver Watt devices… literally, you just plug them in and that’s it! My wife was shocked when we got our first bill and we saved $35! And it’s only gotten better from there… We’ll be customers for life.',
      profileName: 'Kevin Holmes, St. Louis, MO',
      reviewStartsImgSrc:
        'https://powerwattwise.com/es9pwtyk/images/checkout-now-v1/5-stars.png',
      rating: '5/5',
      saved: '$35',
    },
    {
      profilePhotoSrc:
        'https://ik.imagekit.io/ei6mtk4ll/Stopwatts/SW-008/sw-008-card-2.png', // Assuming a placeholder URL
      title: '4.7/5 Verified Rating',
      testimonial:
        'I don’t usually write reviews, but I have to share some numbers with you all… In the first month, we saved $33. The second month, $45. The third month, $52. Fourth month, $55. If that isn’t a strong testimonial, I’m not sure what is!',
      profileName: 'Melisa Houston, Syracuse, NY',
      reviewStartsImgSrc:
        'https://powerwattwise.com/es9pwtyk/images/checkout-now-v1/4.5-stars.png', // Assuming a placeholder URL
      rating: '4.7/5',
      saved: '$55',
    },
    {
      profilePhotoSrc:
        'https://ik.imagekit.io/ei6mtk4ll/Stopwatts/SW-008/sw-008-card-3.png', // Assuming a placeholder URL
      title: '5/5 Verified Rating',
      testimonial:
        'If you’re skeptical, I feel sorry for you. ESaver Watt has really made something special here. I’m not entirely sure how it works, but the savings are REAL!',
      profileName: 'Brenda Shearer, Syracuse, NY',
      reviewStartsImgSrc:
        'https://powerwattwise.com/es9pwtyk/images/checkout-now-v1/5-stars.png', // Assuming a placeholder URL
      rating: '5/5',
      saved: '$50',
    },
    {
      profilePhotoSrc:
        'https://ik.imagekit.io/ei6mtk4ll/Stopwatts/SW-008/sw-008-card-4.png', // Assuming a placeholder URL
      title: '4/5 Verified Rating',
      testimonial:
        'Alright so I ended up buying 3 of these. Put one in my kitchen, one in the bedroom, and one in our living room. After six months, I can confidently say that we’re easily saving at least $50 per month. ESaver Watt is a no brainer. You want to save money each month? Buy a few of these and you’re all set.',
      profileName: 'Wilma Besley, Orlando, FL',
      reviewStartsImgSrc:
        'https://powerwattwise.com/es9pwtyk/images/checkout-now-v1/4.5-stars.png', // Assuming a placeholder URL
      rating: '4/5',
      saved: '$50',
    },
  ];

  newCards.forEach((card) => {
    const swiperSlide = document.createElement('div');
    swiperSlide.className = 'swiper-slide';
    swiperSlide.innerHTML = `
      <div class="card">
        <img src="${card.profilePhotoSrc}" alt="${card.profileName}" style="width:100px; height:100px; border-radius:50%;">
        <h3>${card.profileName}</h3>
        <p>${card.testimonial}</p>
        <img src="${card.reviewStartsImgSrc}" alt="Rating ${card.rating}" style="width:100px;">
        <p>Saved: ${card.saved}</p>
      </div>
    `;
    document.querySelector('.swiper-wrapper').appendChild(swiperSlide);
  });

  // Initialize Swiper
  new Swiper('.customSwiper', {
    grabCursor: true,
    slidesPerView: 2,
    centeredSlides: false,
    spaceBetween: 24,
    loop: false,
    slidesPerGroup: 2,
    updateOnImagesReady: true,
    navigation: {
      nextEl: '.swiper-button-next',
      prevEl: '.swiper-button-prev',
    },
  });
});
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 {
  box-shadow: 0px 10px 30px rgba(0, 0, 0, 0.05);
  height: 100%;
  width: 100%; /* Adjust this to manage the total width of each slide containing two cards */
  flex-shrink: 0;
  padding: 0 !important;
}

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

.swiper-wrapper {
  height: 100%;
  width: 100%;
  align-items: center;
}
.card {
  border-radius: 25px;
  background: #f8f8f8;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.05);
  padding: 20px;
  max-width: 300px;
}

.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>

© www.soinside.com 2019 - 2024. All rights reserved.