【覚書】swiper-slideがひとつだったらセンターに表示させる
swiper-slideが複数の時はデフォルト( 左寄せ )、ひとつの時のみセンター表示にしたい。
≪前提として以下のオプションを設定≫
slidesPerView: “auto”,
spaceBetween: 20,
※ Swiper 4.5.0 使用
HTML(Swiper / Multiple Slides Per View)
<div class="swiper-container"> <div class="swiper-wrapper"> <div class="swiper-slide"><img src="..." alt="..."></div> <div class="swiper-slide"><img src="..." alt="..."></div> <div class="swiper-slide"><img src="..." alt="..."></div> <div class="swiper-slide"><img src="..." alt="..."></div> <div class="swiper-slide"><img src="..." alt="..."></div> </div> <div class="swiper-pagination"></div> </div> <div class="swiper-container"> <div class="swiper-wrapper"> <div class="swiper-slide"><img src="..." alt="..."></div> </div> <div class="swiper-pagination"></div> </div>
Javascript/jQuery
$( function () { $(".swiper-wrapper").each(function() { var swiperSlide = $(this).find('.swiper-slide'); if(swiperSlide.length == 1) { $(this).addClass('justify-content-center'); swiperSlide.addClass('mr-0'); } }); });
CSS
.swiper-slide { width: 280px; } .swiper-slide img { max-width: 100%; height: auto; } .justify-content-center { -webkit-box-pack: center !important; -ms-flex-pack: center !important; justify-content: center !important; } .mr-0 { margin-right: 0 !important; }