LoginSignup
22
24

More than 5 years have passed since last update.

CSS で underline に animation をつける

Posted at

問題

CSS で underline に animation をつけたい。

解決策

::after / :hover / display / transition / width を組み合わせることで実現できる。

結果は https://jsfiddle.net/666xcjhj/ .

<a href="http://bouzuya.net">bouzuya.net</a>
a { text-decoration: none; } /* reset default css */

a {
  display: inline-block;
}

a::after {
  content: "";
  display: block;
  width: 0;
  transition: width 0.3s;
  border-bottom: 1px solid #f00;
}

a:hover::after {
  width: 100%;
}

解説

  • ::after を underline として利用する。
  • transitionwidth により :hover で underline を animation させている。
  • display: inline-block;display: block; は underline の幅をあわせるためにある。
  • content: "";::after を表示するためにある。
  • border-bottom: 1px solid #f00; は underline の装飾なので任意。heightbackground を組み合わせても良い。
  • ::aftermargin: 0 auto; を指定すると「左→右」から「中央→外」に変更できる。
  • line-height によっては ::after が離れてしまうので、position: relative;position: absolute; などで合わせると良い。

参考

22
24
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
22
24