CSSでhover時などにちょっとしたアニメーションをする
昔だったらjQueryの得意技だったhover時のアニメーションですが、今はCSSでやるのが普通ですね。
今でもついjQueryでやってしまうこともありますが、CSSでの方法を書いておきます。
.animation1{
position: relative;
display: block;
width: 200px;
height: 40px;
text-align: center;
text-decoration: none;
}
.animation1:before{
content: '';
position: absolute;
left: 0px;
bottom: 0px;
width: 100%;
height: 6px;
background-color: #aaa;
}
.animation1:after{
content: '';
position: absolute;
left: 0px;
right: 0px;
bottom: 0px;
content: '';
width: 0px;
height: 6px;
margin: 0 auto;
background-color: #e88;
transition: width 2s;
}
.animation1:hover:after{
width: 100%;
transition: width 2s;
}
アニメーションに関する記述は、
transition: width 2s;
の部分のみです。
widthを2s(2秒)かけて変化させる、ということです。
シンプルで簡単ですね。
複数の値を変化させる場合は、,(カンマ)でつなげばOK。
transitionを複数書いてしまうと、当然ですが後に書かれたもので上書きされてしまうので注意してください。
アニメーションの速度などを時間ごとに変化させたい場合や、時間ごとに変化させる属性値を加えていきたい場合は@keyframeが使用できます。
.animation2{
display: block;
width: 300px;
height: 300px;
background-color: #e88;
text-align: center;
padding-top: 150px;
animation: animation2_off 2s forwards linear
}
.animation2:hover{
animation: animation2_on 2s forwards linear
}
@keyframes animation2_off {
0% {
border: #8e8 6px solid;
border-radius: 50%;
}
50% {
border-radius: 40%;
border: transparent 6px solid;
background-color: #faa;
}
100% {
border-radius: 5%;
background-color: #e88;
}
}
@keyframes animation2_on {
0% {
border-radius: 5%;
}
50% {
border-radius: 40%;
border: transparent 6px solid;
background-color: #e88;
}
100% {
border-radius: 50%;
border: #8e8 6px solid;
background-color: #faa;
}
}
細かい設定値などは下記を参照。
