Sửa lỗi Swiper CLS (Cumulative Layout Shift)

Qua công việc mình hay gặp các slider load gây nên tình trạng dịch chuyển bố cục tích luỹ (nói ngắn gọn là khi load trang nó không ổn định làm sai lệch lúc load và lúc hoàn thành tải trang)

Trong bài viết này mình note lại bài viết cho chính mình và giới thiệu nó đến những ai đang sử dụng Swiper slider và gặp phải lỗi CLS (Cumulative Layout Shift)

Để sửa được lỗi này bạn chỉ cần thêm css này vào website của bạn là vấn đề sẽ được giải quyết.

/* Add this class to .swiper element */
.swiper-prevent-content-shift {
  --swiper-sidebar-w: 0px;
  --swiper-slidesPerView: 1;
  --swiper-spaceBetween: 16px;
  --swiper-available-width: 100vw - ( var(--page) * 2 ) - var(--swiper-sidebar-w);
  --swiper-SwiperSlide-width: calc(
    (
      var(--swiper-available-width)
      -
      ( ( var(--swiper-slidesPerView) - 1 ) * var(--swiper-spaceBetween) )
    )
    /
    var(--swiper-slidesPerView)
  );

  @screen lg {
    --swiper-sidebar-w: 14rem;
  }

  .swiper-slide {
    width: var(--swiper-SwiperSlide-width) !important;
    /* Only for horizontal swipers (only horizontal swipers need preventing content shift because vertical ones need fixed width and height) */
    margin-left: var(--swiper-spaceBetween);
  }
}/* Add this class to .swiper element */
.swiper-prevent-content-shift {
  --swiper-sidebar-w: 0px;
  --swiper-slidesPerView: 1;
  --swiper-spaceBetween: 16px;
  --swiper-available-width: 100vw - ( var(--page) * 2 ) - var(--swiper-sidebar-w);
  --swiper-SwiperSlide-width: calc(
    (
      var(--swiper-available-width)
      -
      ( ( var(--swiper-slidesPerView) - 1 ) * var(--swiper-spaceBetween) )
    )
    /
    var(--swiper-slidesPerView)
  );

  @screen lg {
    --swiper-sidebar-w: 14rem;
  }

  .swiper-slide {
    width: var(--swiper-SwiperSlide-width) !important;
    /* Only for horizontal swipers (only horizontal swipers need preventing content shift because vertical ones need fixed width and height) */
    margin-left: var(--swiper-spaceBetween);
  }
}

Nguồn: https://github.com/nolimits4web/swiper/issues/4076

Nếu bạn thấy bài viết có ích hãy sao chép link và chia sẻ bài viết
user

Yêu thích Võ thuật và Công nghệ thông tin, thích viết và chia sẽ về 2 lĩnh vực này thế thôi :D

Bài viết liên quan