1
0

HTMLとCSSのみで画像のアクセプト比を保持したまま、背景画像のスライドショーを実装する

Last updated at Posted at 2024-06-19

はじめに

背景画像のスライドショーを実装したいけど、画像のアクセプト比が歪んでしまったり、javascriptを必要とする場合があったので、HTMLとCSSだけで簡単に実装できるスライドショーの作り方を紹介します。
今回は、3枚の画像でスライドショーを実装しています。

HTMLの記述

index.html.erb
<div class="slideshow">
    <div class="slideshow-image" style="background-image: url('<%= asset_path '画像の名前' %>');"></div>
    <div class="slideshow-image" style="background-image: url('<%= asset_path '画像の名前' %>');"></div>
    <div class="slideshow-image" style="background-image: url('<%= asset_path '画像の名前' %>');"></div>
</div>

こちらを任意の場所に挿入してください。

CSSの記述

index.scss

.slideshow {
  position: relative;
  height: 〇〇px;
  width: 〇〇px;
}

.slideshow-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  animation: slideshow 9s infinite;
  opacity: 0;
}

.slideshow-image:nth-child(1) {
  animation-delay: 0s;
}

.slideshow-image:nth-child(2) {
  animation-delay: 3s;
}

.slideshow-image:nth-child(3) {
  animation-delay: 6s;
}

@keyframes slideshow {
  0%    {opacity: 0; }
  11.1% {opacity: 1; }
  33.3% {opacity: 1; }
  44.4% {opacity: 0; }
  100%  {opacity: 0; }
}

こちらをcssに挿入してみましょう。
およそ3秒おきに画像が変わるスライドショーができていると思います。

CSSの簡単な解説

index.scss

.slideshow {
    position: relative; スライドショーの位置を設定
    height: 〇〇px;
    width: 〇〇px;
  }
  
  .slideshow-image {
    position: absolute; 各画像の位置を設定、親要素に対して絶対的な位置に配置
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-size: cover;
    background-position: center;
    animation: slideshow 9s infinite; 「slideshow」という名前のアニメーションを9秒間で無限に繰り返し
    opacity: 0;  各画像の初期透明度を設定、この場合完全透明
  }
  
  アニメーションの開始時間の設定
  .slideshow-image:nth-child(1) {
    animation-delay: 0s; アニメーションをすぐに開始
  }
  
  .slideshow-image:nth-child(2) {
    animation-delay: 3s; アニメーションを3秒後に開始
  }
  
  .slideshow-image:nth-child(3) {
    animation-delay: 6s; アニメーションを6秒後に開始
  }
  
  キーフレームの定義
  @keyframes slideshow {
    0%    {opacity: 0; } 
    11.1% {opacity: 1; }
    33.3% {opacity: 1; }
    44.4% {opacity: 0; }
    100%  {opacity: 0; }
  }
   0%(開始時)と100%(終了時)には透明度が0(完全に透明に設定)
   11.1%~33.3%の間は透明度が1(完全に不透明に設定)
   44.4%終了までは透明度が0(完全に透明に戻る)

これにより、各画像が順番に表示され、それぞれが3秒間表示された後に次の画像に切り替わるスライドショーが作成されます。今回設定した画像は3枚のため、全体のサイクル時間は9秒です。
細かな数値は調整してみてください。
※このスライドショーは無限に繰り返されます。

おわりに

大学生限定プログラミングコミュニティのGeekSalonでメンターをしてます!
大学生でプログラミング気になる人はぜひHP見てみてね:yellow_heart:
要チェック!大学生限定プログラミングコミュニティGeekSalon

1
0
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
1
0