【CSS】全画面表示の背景画像を左から右、右から左に無限ループ表示させる。

電脳備忘録

本記事のソースコードの利用によって生じた損害について、当方は一切の責任を負いません。ご自身の判断と責任のもとで参照・ご利用ください。

この記事は最終更新から3年以上経過しています。

全画面表示の背景画像を左から右、右から左に無限ループ表示させたいという要望に応えるべく対応した時の備忘録。 負の遺産であるIEを気にしなくていいのでCSSのみで実装。

【CSS3】背景画像を無限スクロールさせる[Infinite Scrolling Background]がカッコいいですよ。
body {
  background: url(img/bg.jpg) repeat-x;
  background-position:center center;
  position:fixed;
  top:0;
  left:0;
  right:0;
  bottom:0;
  /*背景ループの速度調整*/
  animation:infinitescroll 25s linear infinite;
  z-index:0;            
}

/*左から右に流す*/
@keyframes infinitescroll {
 0% {background-position:0 0;}
 100% {background-position:100vw 0;}
}

右から左に流す場合。

  
@keyframes infinitescroll {
  0% {background-position:0 0;}
  100% {background-position:-100vw 0;}
}

全体はこんな感じ。

  
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>背景無限ループテスト</title>
    <style>
      body {
        background: url(img/bg.jpg) repeat-x;
        background-position:center center;
        position:fixed;
	top:0;
	left:0;
	right:0;
	bottom:0;
	/*背景ループの速度調整*/
	/*念のためベンダープレフィックスつけとく、もう不要かもだけど*/
	-webkit-animation:infinitescroll 25s linear infinite;
	-moz-animation:infinitescroll 25s linear infinite;
	-ms-animation:infinitescroll 25s linear infinite;
	-o-animation:infinitescroll 25s linear infinite;
	animation:infinitescroll 25s linear infinite;
	z-index:0;            
      }
      
      /*左から右に流す*/
      /*念のためベンダープレフィックスつけとく、もう不要かもだけど*/
      @-webkit-keyframes infinitescroll {
	0% {background-position:0 0;}
	100% {background-position:100vw 0;}
      }
      @-moz-keyframes infinitescroll {
	0% {background-position:0 0;}
	100% {background-position:100vw 0;}
      }
      @-ms-keyframes infinitescroll {
	0% {background-position:0 0;}
	100% {background-position:100vw 0;}
      }
      @-o-keyframes infinitescroll {
	0% {background-position:0 0;}
	100% {background-position:100vw 0;}
      }
      @keyframes infinitescroll {
	0% {background-position:0 0;}
	100% {background-position:100vw 0;}
      }

      #container {
        margin: 50px auto 0px;
        width: 800px;
        background: #FFFFFF;
        padding: 30px;
        height: 500px;
      }
    </style>
</head>
<body>
  <div id="container">
    <h1>cssでバックグラウンドを無限ループ</h1>
    <p>このページはcss animationでバックグランド画像をアニメーションループさせるサンプルページです。</p>
  </div>  
</body>
</html>
0%