Reputation:
I am trying to move an HTML element up about 10px whenever a user hovers their mouse over it. I did some research on w3schools, but I could not find any information that helped me. Most of their animation examples were using keyframes and I'm pretty sure that's not what I need because I'm trying to trigger an animation when somebody hovers over the element. I could be wrong though and that's why I'm posting here.
Here's the element I'm trying to move:
<div id="arrow">
<a href="#"><i class="fa fa-arrow-down fa-2x"></i></a>
</div>
For my CSS:
#arrow {
padding-top: 310px;
color: #5C6B7E;
position: relative;
/* some kind of animation property here? */
}
#arrow:hover {
/* new properties once user hovers */
}
I'm not sure what I need to add to make the element animate up, the examples on w3schools weren't of much help. If anybody could point me in the right direction I would be extremely appreciative. Thank you Stack Overflow.
Upvotes: 43
Views: 131239
Reputation: 32285
You need not use keyframes for this simple animation. Just CSS transition is enough.
Set the transition
property in the initial state style rules with the duration.
Edit: I just noticed that there is a flicker at the bottom, it can be removed by setting the styles on the icon and hover on the parent.
#arrow i {
position: relative;
top: 0;
transition: top ease 0.5s;
}
#arrow:hover i {
top: -10px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<div id="arrow">
<a href="#"><i class="fa fa-arrow-down fa-2x"></i></a>
</div>
Upvotes: 82
Reputation: 315
I came across this while trying to solve an issue I had with getting an element to move when hovering over it with my mouse. None of the above worked, so I thought I'd share the solution I came up with on a test I ran:
.item {
background-color: black;
display: flex;
width: 100px;
height: 40px;
align-items: center;
justify-content: center;
text-align: center;
color: white;
transition: transform ease 300ms;
}
.item:hover {
transform: translate(0, -10px);
}
<div class="item">TEST</div>
Upvotes: 10
Reputation: 31992
You could also try applying a negative margin-top
on hover if your element is absolutely positioned:
div {
padding: 1em;
border: 1px solid #b5b5b5;
border-radius: 10px;
width: fit-content;
transition: 0.5s;
}
div:hover {
box-shadow: 0 0 3px black;
margin-top: -10px;
}
<br/>
<div>
<img src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1">
</div>
Upvotes: 13