0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CSSのみで作る自動再生カルーセル(スライドショー)

Posted at

同内容は、すでにあちらこちらにあふれているところ、お目汚し失礼します。

できあがったもの

こちら https://codepen.io/sengokyu/pen/poRWzOr に置いています。

仕組み

3枚の画像でやる場合です。

  • 画像①、画像②、画像③、画像①を横に並べる。
  • 画像1枚分だけ見えるように、画像全体をoverflow: hidden;なコンテナで包む。
  • 左端の画像のmargin-leftを負の値にするアニメーションを設定する。

画像を横に並べる

まず、画像を隙間なく並べます。
右端の画像は、左端と同じものにします。

<div class="center slide"
  ><img src="https://i.imgur.com/Y8WHhk2.jpg"
  ><img src="https://i.imgur.com/r0o8RoH.png"
  ><img src="https://i.imgur.com/ioUKL1K.jpg"
  ><img src="https://i.imgur.com/Y8WHhk2.jpg"
></div>

改行せず横並びになるようにします。

.slide {
  white-space: nowrap;
}

画像全体をoverflow: hidden;なコンテナで包む

画像1枚だけ見えるように、overflow: hiddenなコンテナで包みます。サイズも指定します。

.slide {
  white-space: nowrap;
  width: 300px;
  height: 300px;
  overflow: hidden;  
}

画像のサイズもコンテナにあわせます。

.slide img {
  width: inherit;
  height: inherit;
  margin: 0;
  padding: 0;
  border: none;
}

左端の画像のmargin-leftを負の値にするアニメーションを設定する

まずキーフレームを作成します。
画像が3つ(重複分で+1)あるので、キーフレーム4つです。
キーの進行に応じて、100%ずつ左へずらします。

@keyframes slide-4 {
  0% { margin-left: 0; }
  33% { margin-left: -100%; }
  66% { margin-left: -200%; }
  100% { margin-left: -300%; }
}

左端の画像(先頭子要素)にアニメーションを設定します。

.slide > :first-child {
  animation-name: slide-4;     /* 作成したキーフレームを使う */
  animation-duration: 5s;    /* アニメーション全体を5秒にする */
  animation-delay: 0s;       /* 直ちにアニメーション開始する */
  animation-iteration-count: infinite; /* 永遠にアニメーションする */
}

画像の枚数を増減させるときは……

キーフレームの数を調整してください。

例えば、画像4つ(重複分で+1)のときはこうなります。

@keyframes slide-4 {
  0% { margin-left: 0; }
  25% { margin-left: -100%; }
  50% { margin-left: -200%; }
  75% { margin-left: -300%; }
  100% { margin-left: -400%; }
}

参考リンク

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?