Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS animate border in and out

Tags:

html

css

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

like image 455
Daniel G Avatar asked Jul 18 '17 13:07

Daniel G


People also ask

Can you animate border in CSS?

CSS border animation is useful for giving a border image or container element a unique style. To make a website's user interface (UI) more attractive, use a CSS border animation design. CSS border animation is useful for giving a border image or container element a unique style.


2 Answers

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>
like image 134
Chiller Avatar answered Oct 04 '22 23:10

Chiller


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>
like image 39
Mohammad Usman Avatar answered Oct 05 '22 01:10

Mohammad Usman