CSS

CSSアニメーション入門|transitionとkeyframesの使い方

CSS アニメーション トランジション

CSSアニメーション入門
transitionとkeyframesの使い方

CSSだけでホバーエフェクト、フェードイン、スライドインなどのアニメーションを実装できます。
JavaScriptなしで実現できるCSSアニメーションの基本を解説します。

こんな人向けの記事です

  • ボタンやリンクにホバーエフェクトを付けたい
  • ページ要素にフェードインアニメーションを追加したい
  • transitionとanimationの違いを理解したい

Step 1transition:状態変化にアニメーション

transition は、CSSプロパティが変化する時にアニメーションを付けます。ホバーやクラスの追加時に使います。

CSS
.button {
  background: #3498db;
  color: white;
  padding: 10px 30px;
  border: none;
  border-radius: 4px;
  transition: background-color 0.3s, transform 0.3s;
}

.button:hover {
  background: #2980b9;
  transform: scale(1.05);
}

Step 2transitionのプロパティ詳細

プロパティ役割
transition-propertyアニメーション対象のプロパティbackground-color, all
transition-durationアニメーションの時間0.3s, 500ms
transition-timing-function加速・減速のカーブease, linear
transition-delayアニメーション開始の遅延0.1s
CSS
/* ショートハンド */
transition: プロパティ 時間 タイミング 遅延;

/* 例 */
transition: all 0.3s ease;
transition: background-color 0.5s ease-in-out 0.1s;

/* 複数プロパティ */
transition: background-color 0.3s, transform 0.3s, opacity 0.5s;
タイミング関数の種類
ease → ゆっくり始まり、速くなり、ゆっくり終わる(デフォルト)
linear → 一定速度
ease-in → ゆっくり始まる
ease-out → ゆっくり終わる
ease-in-out → ゆっくり始まり、ゆっくり終わる

Step 3@keyframes:複雑なアニメーション

@keyframes を使うと、複数の段階を持つアニメーションを定義できます。

CSS
@keyframes bounce {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-20px);
  }
}

.ball {
  width: 60px;
  height: 60px;
  background: #e74c3c;
  border-radius: 50%;
  animation: bounce 1s ease-in-out infinite;
}

Step 4animationのプロパティ詳細

プロパティ役割
animation-name@keyframesの名前bounce
animation-duration1回の時間1s
animation-timing-function加速カーブease-in-out
animation-delay開始の遅延0.5s
animation-iteration-count繰り返し回数infinite, 3
animation-direction再生方向alternate
animation-fill-mode終了後の状態forwards
CSS
/* ショートハンド */
animation: 名前 時間 タイミング 遅延 回数 方向 fill-mode;

/* 例 */
animation: bounce 1s ease-in-out infinite;
animation: fadeIn 0.5s ease forwards;

Step 5実践:よく使うアニメーションパターン

フェードイン

CSS
@keyframes fadeIn {
  from { opacity: 0; }
  to   { opacity: 1; }
}

.fade-in {
  animation: fadeIn 0.5s ease forwards;
}

スライドイン(左から)

CSS
@keyframes slideInLeft {
  from {
    transform: translateX(-100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

.slide-in {
  animation: slideInLeft 0.5s ease forwards;
}

回転(ローディング)

CSS
@keyframes spin {
  from { transform: rotate(0deg); }
  to   { transform: rotate(360deg); }
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #ddd;
  border-top-color: #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

まとめ

  • transition → 状態変化(hover等)のアニメーション
  • @keyframes + animation → 複雑な多段階アニメーション
  • ホバーエフェクトには transition が最適
  • ローディングやフェードインには animation を使う
  • animation-fill-mode: forwards でアニメーション終了後の状態を保持