I tried to make an animation that is triggered on hover and hover out. I didn't use the transition property because the animations are quite complex.
- on hover in: zoom-in the element from 100% => 150% => 130%
- on hover out: zoom-out the element from 130% => 80% => 100%
The hover-in works perfectly, but the hover-out always running at startup. It should animate when has been hover-in.
Then tried to set the CSS var --anim-hover-out: none
, so no animation on startup. Then, on the end of hover-in, set --anim-hover-out: hover-out
, so the hover-out animation now ready to play. But setting the CSS var inside @keyframes
didn't work.
The goal is: .test:not(:hover):has-hover { do hover-out animation }
Note: no JavaScript, pure CSS only.
body {
font-family: 'Lucida Grande', 'Helvetica Neue', Helvetica, Arial, sans-serif;
padding: 100px;
font-size: 13px;
}
div {
background: #eee;
margin: 0 auto;
width: 200px;
padding: 100px;
text-align: center;
/* border-radius */
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
/* box-shadow */
-webkit-box-shadow: rgba(0,0,0,0.2) 0px 1px 3px;
-moz-box-shadow: rgba(0,0,0,0.2) 0px 1px 3px;
box-shadow: rgba(0,0,0,0.2) 0px 1px 3px;
}
:root {
--anim-hover-out: unset;
}
.test:not(:hover) {
animation-name: var(--anim-hover-out);
animation-duration: 500ms;
animation-fill-mode: both;
}
.test:hover {
animation-name: hover-in;
animation-duration: 500ms;
animation-fill-mode: both;
}
@keyframes hover-in {
0: {
transform: scale(1);
}
50% {
transform: scale(1.5);
}
100% {
transform: scale(1.3);
--anim-hover-out: hover-out;
}
}
@keyframes hover-out {
0: {
transform: scale(1.3);
}
50% {
transform: scale(0.8);
}
100% {
transform: scale(1);
}
}
<div class="test">Hello World!</div>