CSS Grid 下 Swiper 计算宽度错误, 导致页面整体布局错乱

问题

"swiper": "8.1.4"

<style>
.swiper_box {
  display: grid;
  grid-template-rows: auto minmax(0, 1fr) auto;
  grid-template-areas:
    "head"
    "body"
    "foot";
  min-height: 100vh;
}

.swiper_head {
  grid-area: head;
}
.swiper_body {
  grid-area: body;
}
.swiper_foot {
  grid-area: foot;
}
</style>
<div className="swiper_box">
  <div className="swiper_head"> header</div>
  <div className="swiper_body">
    <Swiper
      spaceBetween={30}
      effect={"fade"}
      navigation={true}
      pagination={{
        clickable: true
      }}
      modules={[EffectFade, Navigation, Pagination]}
      className="mySwiper"
    >
      <SwiperSlide>
        <img src="https://swiperjs.com/demos/images/nature-1.jpg" />
      </SwiperSlide>
      <SwiperSlide>
        <img src="https://swiperjs.com/demos/images/nature-2.jpg" />
      </SwiperSlide>
      <SwiperSlide>
        <img src="https://swiperjs.com/demos/images/nature-3.jpg" />
      </SwiperSlide>
      <SwiperSlide>
        <img src="https://swiperjs.com/demos/images/nature-4.jpg" />
      </SwiperSlide>
    </Swiper>
  </div>
  <div className="swiper_foot">footer</div>
</div>

原因

grid 容器中设置了行 'fr' 下 swiper 会占用所有空间并进入无穷大

解决方法

  1. 指定 swiper 容器宽度(不能为100%)
  2. swiper_box 新增 grid-template-columns: 100%; 样式,
    若 slidesPerView > 1 需在 Swiper 外层容器添加 overflow: hidden;
  3. swiper_body 新增 overflow: hidden; , overflow hidden子元素无法 position sticky 无法生效
  4. 改用 flex 布局

code

https://codesandbox.io/s/swiper-effect-fade-react-forked-239iuh

参考文献

posted @ 2022-06-21 19:39  fwxin  阅读(578)  评论(0编辑  收藏  举报