@keyframesの記述方法まとめ
1. @keyframesとは
- CSSアニメーションで「動き方」を定義するための仕組み
- 時間の経過に合わせて、スタイル(プロパティ)を段階的に変化させる
2. 基本構文
@keyframes アニメーション名 {
0% {
/* 開始時のスタイル */
}
50% {
/* 中間時点のスタイル(任意) */
}
100% {
/* 終了時のスタイル */
}
}
0%と100%はそれぞれ、from
とto
と書くこともできる
@keyframes アニメーション名 {
from {
/* 開始時 (0%) */
}
to {
/* 終了時 (100%) */
}
}
3. 設定できる内容
項目 | 内容 |
---|---|
アニメーション名 | 任意の名前 |
キーフレーム(%) | 0%〜100%の間でスタイルを指定する |
使用できるスタイル | 通常のCSSプロパティ |
4. 使用例
例1:透明度を変えるアニメーション
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
例2:背景色を変えるアニメーション
@keyframes colorChange {
0% {
background-color: red;
}
50% {
background-color: yellow;
}
100% {
background-color: green;
}
}
5. アニメーションの適用方法
アニメーションを要素に適用するには、animation
プロパティを使用する
プロパティ名 | 内容 |
---|---|
animation-name | アニメーション名 |
animation-duration | アニメーションの再生時間 |
animation-timing-function | 動きの速さ(タイミング関数) |
animation-delay | 開始までの待ち時間 |
animation-iteration-count | 繰り返し回数 |
animation-direction | 再生する方向 |
animation-fill-mode | アニメーション後の状態 |
例:
.box {
display: inline-block;
width: 100px;
height: 100px;
background-color: black;
animation: fadeIn 1.4s;
animation-timing-function: ease;
animation-delay: 2s;
animation-iteration-count: infinite;
animation-direction: alternate-reverse;
animation-fill-mode: forwards;
}
この設定により、
-
fadeIn
(@keyframes
で設定)を1.4秒かけて再生(fadeIn 1.4s
) - 「遅い」→「速い」→「遅い」という速度で動きが変化(
ease
) - 2秒後にアニメーション開始(
2s
) - 無限に繰り返す(
infinite
) - 終わると逆方向(縮小)で再生(
alternate-reverse
) - 最終状態を保持する(
forwards
)
というアニメーションが作られる
まとめ
-
@keyframes
は動きを細かくコントロールできる -
0%〜100%
、またはfrom〜to
でスタイルを変化させる -
animation
プロパティで要素に適用する