Reputation: 63
I'm using the following css to animate a border on hover:
.item {
height: 250px;
width: 250px;
display: block;
background: orange;
-webkit-transition: all .5s ease-in-out;
transition: all .5s ease-in-out;
}
.item:hover {
border: 8px solid green;
}
It works on hover but when I move the mouse out, the border disappears without an animation. Is it possible to slide the border out as well?
https://codepen.io/anon/pen/rwgZXp
Upvotes: 6
Views: 5401
Reputation: 1417
It's normal this happens because you haven't added a border. The border comes only with hover effect. So when you took the mouse pointer out browser doesn't know whether there was a border or not. So you have to add a border with 0px size as mentioned below.
.item {
height: 250px;
width: 250px;
display: block;
border: 0px solid green;
background: orange;
-webkit-transition: all .5s ease-in-out;
transition: all .5s ease-in-out;
}
.item:hover {
border: 8px solid green;
}
I hope this would give you what you want exactly.
Upvotes: 0
Reputation: 9738
You can resolve the issue by animating only border-width
See result:
.item {
height: 250px;
width: 250px;
display: block;
background: orange;
-webkit-transition: all .5s ease-in-out;
transition: all .5s ease-in-out;
border: 0px solid green;
}
.item:hover {
border-width: 8px;
}
<div class="item"></div>
Upvotes: 6
Reputation: 2974
In order for an animation to work, the value you are animating must have a defined amount to animate from and to.
As you never initially set a value for border, the animation has nothing to animate back to when your mouse leaves the element.
The fix for this is to set the initial border to border:0 solid green;
. The hover animation will then smoothly animate from 0 to 8px on hover and smoothly back down to 0 on mouseleave.
Upvotes: 3
Reputation: 22919
You could add a transparent border to the div initially. Then animate the colour. In order to preserve the width and height of the div add box-sizing: border-box
...
.item {
height: 250px;
width: 250px;
display: block;
background: orange;
box-sizing: border-box;
border: 8px solid transparent;
-webkit-transition: all .5s ease-in-out;
transition: all .5s ease-in-out;
}
.item:hover {
border: 8px solid green;
}
<div class="item"></div>
Upvotes: 0
Reputation: 39322
Add transparent border on .item
and change color on hover.
.item {
border: 8px solid transparent;
background-clip: content-box;
}
.item:hover {
border-color: green;
}
Also note the use of background-clip
property. This will limit background color only to the content area excluding borders.
.item {
height: 250px;
width: 250px;
display: block;
background: orange;
border: 8px solid transparent;
background-clip: content-box;
-webkit-transition: all .5s ease-in-out;
transition: all .5s ease-in-out;
}
.item:hover {
border-color: green;
}
<div class="item"></div>
Upvotes: 4