ブルーシュ

IT技術の勉強記録

ホーム > Tips > WordPress > フロントエンド

Swiper スマホ版だけレスポンシブにしたい

, , , , ,

便利なスライダーライブラリ「Swiper」。今回のお悩みは、

です。

Swiper 基本の使い方
Swiperのバージョンは8です。
 
※例として、PC版の画像1枚の大きさを1024px * 768pxとして進めます。


 

HTML側の設定


<div id="slider">

	<div class="swiper">
		<div class="swiper-wrapper">

			<タグ class="swiper-slide"></タグ>
			<タグ class="swiper-slide"></タグ>
			<タグ class="swiper-slide"></タグ>

		</div>
	</div>

</div>

ポイントは.swiper-containerさらに入れ子にしてるところ。例では#sliderというID名。
.swiper-slideaタグでもいいし、<picture>または <img>でもOK。
 
srcsetsizesでレスポンシブ対応も可能です。

レスポンシブ画像を使った場合の例

<div id="slider">

	<div class="swiper">
		<div class="swiper-wrapper">

			<picture class="swiper-slide">
				<source media="(max-width: 799px)" srcset="1_sp.jpg">
				<source media="(min-width: 800px)" srcset="1.jpg">
				<img src="1.jpg" alt="***">
			</picture>

			<picture class="swiper-slide">
				<source media="(max-width: 799px)" srcset="2_sp.jpg">
				<source media="(min-width: 800px)" srcset="2.jpg">
				<img src="2.jpg" alt="***">
			</picture>

			<picture class="swiper-slide">
				<source media="(max-width: 799px)" srcset="3_sp.jpg">
				<source media="(min-width: 800px)" srcset="3.jpg">
				<img src="3.jpg" alt="***">
			</picture>

		</div>
	</div>
</div>

参考:レスポンシブ画像 - ウェブ開発を学ぶ | MDN
 

設定ファイル

スライドを動かすための、JavaScriptの設定。


const swiper = new Swiper('.swiper', {
	centeredSlides: true,
	loop: true,
	slidesPerView: 1.25,
	spaceBetween: 0,
	effect:"slide",
	breakpoints: {
		1025: {
			width:1024,
			height:768,
			slidesPerView: "auto"
		}
	}
});

ポイントはbreakpointsを使う点です。Swiperのbreakpointsは、「〇〇px以上~」という切り替えで活用します。なのでスマホ版がまず基本となり、PC版の動作をbreakpointsの中に書いていきます。
例では画面幅1025px以上で固定表示に切り替わります。スマホ版では常に画像は画面比率に応じて伸縮します。slidesPerView: 1.25にしてるので左右に前後の画像がちょっと見えてるということです。centeredSlides: trueもセットで設定してください。
このJSファイルは、swiper-bundle.min.jsのあとに読み込んでください。
 

CSS側の設定


#slider{
	width:100%;
	overflow: hidden;
}.swiper-container, .swiper-wrapper{
	margin: 0 auto;
}.swiper-slide img{
	max-width: 100%;
	height: auto;
}
@media screen and (min-width:  1025px){
	.swiper-wrapper{
		width:100%;
		padding-left:calc(50% - (1024px / 2));
		height:768px;
	}.swiper-slide{
		width:1024px !important;
		height:768px !important;
	}
}

#sliderは画面幅より小さくならないようにしてください。
.swiper-container, .swiper-wrappermargin: 0 auto;にして真ん中寄せにします。
画面幅が1025px以上になると、スライダーは固定表示になります。JSの設定でcenteredSlides: trueにしているのですが、なぜかスライダーが画面の左端に寄ってしまうため、padding-left:calc(50% – (1024px / 2));で真ん中寄せにしています。
 
1024や768の数字はお好みで変更してください。
 

参考になりそうなTips

Swiper スマホ版だけレスポンシブにしたい #フロントエンド #ウェブデザイン #ウェブ制作 #WEBデザイン #WEB制作 #css #JavaScript #レスポンシブ #画像 #スライダー #Swiper

作者の似顔絵

プログラミング歴19年🌈調べたことをブログにまとめていきます。
記事の感想・質問・間違い指摘などはツイッター ( @blooshcompany ) へお願いします。

秋田のウェブ活用をサポート

ホームページを自作してコスト削減!秋田の事業者は無料で利用できます。
ネットショップ・WordPress・SEO対策などさまざまなお悩みをサポートします。

その他、フロントエンド案件のご依頼はインフォメーション

秋田市 レンタル着物 笹パンダ堂のバナーリンク