CSS3によるアニメーションは大きく分けて、トランジション(transition)とアニメーション(animation)の2つに別ける事が出来ます。
CSS3におけるトランジション(transition)とアニメーション(animation)の違い
「transition」
- 動かすために:hoverなどのきっかけが必要
- トランジションでは実行後に元のプロパティ値に戻る
- 比較的簡単な記述で動かす事が可能
「animation」
- transitionより細かい設定が可能
- 記述が複雑
- 「@keyframes」の記述が必要
http://caniuse.com/などのサイトでブラウザサポート状況を確認する。
animation関連プロパティ
animation-name 必須
@keyframes で定義した名前を指定します。これを指定していないとアニメーションは実行されません。
animation-duration 必須
一回分のアニメーションを実行する時間の長さを指定します。
animation-timing-function
アニメーションのタイミングや進め方を指定します。
ease(初期値)
ease-in
ease-out
ease-in-out
linear
animation-delay
要素が読み込まれてからアニメーションがいつ始まるかを指定します。初期値の 0 だとただちに実行されます。
animation-iteration-count (初期値は1)
アニメーションを繰り返す回数を数字で指定します。無限ループにするには infinite を指定。
animation-direction
アニメーションを繰り返す方向を指定します。
normal … 通常の方向で再生(初期値)
alternate … 奇数回で通常・偶数回で反対方向に再生(行って帰って行って帰って…という具合)
reverse … 逆方向に再生
alternate-reverse … alternate の逆方向に再生
animation-fill-mode
アニメーションの再生前後の状態を指定します。
none(初期値)
forwards … 再生後、最後のキーフレームの状態を保持
backwards … 再生前、最初のキーフレームの状態を適用
both … forwards と backwards の両方を適用
背景色が移り変わるアニメーション
body { background-color: #0CC; animation: bg-color 10s linear infinite; -webkit-animation: bg-color 10s linear infinite; } @-webkit-keyframes bg-color { 0% { background-color: #0CC; } 20% { background-color: #f1c40f; } 40% { background-color: #1abc9c; } 60% { background-color: #3498db; } 80% { background-color: #9b59b6; } 100% { background-color: #0CC; } } @keyframes bg-color { 0% { background-color: #0CC; } 20% { background-color: #f1c40f; } 40% { background-color: #1abc9c; } 60% { background-color: #3498db; } 80% { background-color: #9b59b6; } 100% { background-color: #e74c3c; } }
参考サイト
CSS3でアニメーション!transitionとanimationまとめ(サンプル付き) – フラップイズム
CSS3アニメーションに挑戦!色が移り変わる背景を実装しよう | Webクリエイターボックス
bodyに背景画像を置き、#container の背景色をアニメーションで動かします。
bodyの背景画像が見えるように#containerには背景色をrgbaを使って半透明で指定しましょう。
body { background-image: url(img/bg.png); /* 画像を常に天地左右の中央に配置 */ background-position: center center; /* 画像を繰り返し表示しない */ background-repeat: no-repeat; /* コンテンツの高さが画像の高さより大きい時、動かないように固定 */ background-attachment: fixed; /* 表示するコンテナの大きさに基づいて、背景画像を調整 */ background-size: cover; /* 背景画像が読み込まれる前に表示される背景のカラー */ background-color: #464646; } #container { height: 3000px; padding-top: 30px; background: rgba(231, 76, 60, 0.5); /*アニメーション*/ -webkit-animation: bg-color 20s infinite; animation: bg-color 20s infinite; } @-webkit-keyframes bg-color { 0% { background-color: rgba(231, 76, 60, 0.5); } 20% { background-color: rgba(123, 76, 60, 0.5);} 40% { background-color: rgba(222, 76, 60, 0.5);} 60% { background-color: rgba(153, 76, 60, 0.5); } 80% { background-color: rgba(23, 76, 60, 0.5); } 100% { background-color:rgba(231, 76, 60, 0.5); } } @keyframes bg-color { 0% { background-color: rgba(231, 76, 60, 0.5); } 20% { background-color: rgba(123, 76, 60, 0.5);} 40% { background-color: rgba(222, 76, 60, 0.5);} 60% { background-color: rgba(153, 76, 60, 0.5); } 80% { background-color: rgba(23, 76, 60, 0.5); } 100% { background-color:rgba(231, 76, 60, 0.5); } }