LoginSignup
58
48

More than 3 years have passed since last update.

CSSの:hoverアニメーションで、マウスオーバー/アウト時の処理を変化させる

Last updated at Posted at 2015-09-18

:hover擬似クラスとCSSアニメーションを組み合わせることで、ボタン要素などの簡易的なマウスオーバーアニメーションを実現できます。

1秒かけて背景色がアニメーションするボタン

HTML

<button type="button">ボタン</button>

CSS

button {
    background-color: #f00;

    /* 1秒かけて背景色をアニメーションさせる */
    transition: background-color 1s;
}

button:hover {
    /* マウスオーバー時に背景色をグレーに変更 */
    background-color: #333;
}

See the Pen pozWWGO by Sho Uchida (@shouchida) on CodePen.

マウスアウト時はもっと素早く変化させたい

上記の例では、マウスオーバー時とマウスアウト時のアニメーション速度はどちらも「1秒」になります。

「マウスアウト時のアニメーション速度は0.5秒にしたい」など、マウスオーバー/アウト時の処理を変化させたい場合は、通常時と:hover擬似クラスの両方に transition プロパティを指定します。

CSS

button {
    background-color: #f00;

    /* マウスアウト時、0.5秒かけて背景色をアニメーションさせる */
    transition: background-color 0.5s;
}

button:hover {
    background-color: #333;

    /* マウスオーバー時、1秒かけて背景色をアニメーションさせる */
    transition: background-color 1s;
}

See the Pen mdbBBNm by Sho Uchida (@shouchida) on CodePen.

アニメーション対象プロパティを増やして複雑な動きを実現する

transition プロパティは、対象とするCSSプロパティを「カンマ区切りで複数」設定できるため、記述の仕方によってより複雑なアニメーションも実現できます。

下記の例では background-color と border-radius の2つのプロパティをそれぞれ異なる速度で変化させています。

CSS

button {
    background-color: #f00;
    transition: background-color 0.5s, border-radius 1s;
}

button:hover {
    background-color: #333;
    border-radius: 20px;
    transition: background-color 1s, border-radius 2s;
}

See the Pen jONGGgv by Sho Uchida (@shouchida) on CodePen.

58
48
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
58
48