Archive

Archive

画像が変わっていくCSS

  • ホーム
  • Archive
  • 画像が変わっていくCSS
2025.11.26コード

JavaScriptを使用せず、画像が自動で変わっていくCSSです。
画像の大きさはchageImageBoxの幅と比率から変更してください。
5枚の画像が次々に変わります。

デモページはこちら

<div class="chageImageBox">
<figure><img src="img/hogehoge.jpg" /></figure>
<figure><img src="img/hogehoge.jpg" /></figure>
<figure><img src="img/hogehoge.jpg" /></figure>
<figure><img src="img/hogehoge.jpg" /></figure>
<figure><img src="img/hogehoge.jpg" /></figure>
<figure><img src="img/hogehoge.jpg" /></figure>
<!-- /.chageImageBox --></div>
.chageImageBox{
width: 40em; //画像の幅はここで修正する
aspect-ratio:3/2; //画像の比率はここで修正する
position: relative;
display:block;
}

.chageImageBox>figure {
width:100%;
height:100%;
display:flex;
align-content:center;
justify-content:center;
opacity: 0;
margin:0;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
animation: animeImageSwitch 25s infinite;
}
.chageImageBox:hover>figure {
animation-play-state: paused;//ホバーで一時停止
}

.chageImageBox>figure img{
width:100%;
object-fit: cover;
}

.chageImageBox>figure:nth-of-type(1) {
  animation-delay: 0s;
}
.chageImageBox>figure:nth-of-type(2) {
  animation-delay: 5s;
}
.chageImageBox>figure:nth-of-type(3) {
  animation-delay: 10s;
}
.chageImageBox>figure:nth-of-type(4) {
  animation-delay: 15s;
}
.chageImageBox>figure:nth-of-type(5) {
  animation-delay: 20s;
}

@keyframes animeImageSwitch {
0%{ opacity: 0;}
5%{ opacity: 1;}
25%{ opacity: 1;}
30%{ opacity: 0;}
100%{ opacity: 0;}
}
.chageImageBox{
  width: 40em;
  aspect-ratio: 3 / 2;  //画像の比率はここで修正する
  position: relative;
  display:block;
  &>figure {
    width:100%;
    height:100%;
    display:flex;
    align-content:center;
    justify-content:center;
    opacity: 0;
    margin:0;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    animation: animeImageSwitch 25s infinite;
    img{
      width:100%;
      object-fit: cover;
    }
    &:nth-of-type(1) {
      animation-delay: 0s;
    }
    &:nth-of-type(2) {
      animation-delay: 5s;
    }
    &:nth-of-type(3) {
      animation-delay: 10s;
    }
    &:nth-of-type(4) {
      animation-delay: 15s;
    }
    &:nth-of-type(5) {
      animation-delay: 20s;
    }
  }
  &:hover>figure {
    animation-play-state: paused;
  }
}

@keyframes animeImageSwitch {
0%{ opacity: 0;}
5%{ opacity: 1;}
25%{ opacity: 1;}
30%{ opacity: 0;}
100%{ opacity: 0;}
}

デモページはこちら

1枚5秒が5枚あり、合計25秒で変わります。
これは、「 animation: animeImageSwitch 25s infinite;」から時間を変更できます。
各画像は5秒ずつ遅らせてアニメーションしている。
アニメーション「animeImageSwitch」で
25秒の5%の間、1.25秒でフェードしています。
25秒の5%~25%の間、20%で5秒間、画像が表示されます。
枚数を変更する場合 CSSは、
・アニメーションの合計時間
・アニメーションを遅らせる時間
・アニメーションの画像表示させる時間
の3つを変更する必要があります。

ページ上部に戻るスプーン