🎨

text-decoration: underlineにtransition効果を適用させる方法

に公開

CSSで下線(underline)にスムーズなアニメーション効果を付けたい場合、text-decoration: underlineに直接transitionを適用しても期待通りに動作しません。

よく::after::beforeなどの疑似要素を使った方法が紹介されますが、これらは左から右に広がるアニメーションや複雑なカスタマイズが必要な場合には有効です。しかし、純粋にただ下線をスムーズに表示したいだけの場合には少し冗長です。

この記事では、シンプルに下線のtransition効果を実現するより直接的で実用的な方法に焦点を当てて解説します。

問題:text-decorationはtransitionが効かない

css
/* これは動作しません */
.text {
  text-decoration: none;
  transition: text-decoration 0.5s ease;
}

.text:hover {
  text-decoration: underline;
}

text-decorationプロパティはtransitionが適用されないため、上記のコードでは瞬間的に下線が表示されてしまいます。

解決方法1: text-decoration-colorを使用(直接的な解決)

text-decoration自体はtransitionが効きませんが、text-decoration-colorには適用できます。これが最も直接的な解決方法です。

css
.text-decoration-underline {
  text-decoration: underline;
  text-decoration-color: transparent;
  text-decoration-thickness: 1px;
  transition: text-decoration-color 0.5s ease;
}

.text-decoration-underline:hover {
  text-decoration-color: currentColor;
}
html
<a href="#" class="text-decoration-underline">text-decorationにtransitionを適用させた下線</a>

解決方法2: border-bottom-colorを使用(代替手段)

border-bottomを使用した代替手段もあります。古いブラウザサポートが必要な場合や、より確実に動作させたい場合はこちらを使うと良いと思います。(あまり多くはないと思いますが)

css
.border-underline {
  display: inline-block;
  text-decoration: none;
  border-bottom: 1px solid transparent;
  transition: border-bottom-color 0.5s ease;
}

.border-underline:hover {
  border-bottom-color: currentColor;
}
html
<a href="#" class="border-underline">border-bottomにtransitionを適用させた下線</a>

デモ

実際の動作は以下のCodePenで確認できます:

まとめ

::after疑似要素を使わずに下線にスムーズなアニメーション効果を適用する方法を2つ紹介しました:

  • text-decoration-color: 最も直接的で自然な解決方法。text-decorationtransition問題を根本的に解決(サポート状況
  • border-bottom-color: 互換性が高く確実に動作。古いブラウザサポートが必要な場合におすすめ(サポート状況

プロジェクトのブラウザサポート要件に応じて、適切な手法を選択してください。

Discussion