Hover leaving Animation

Viewed 586

When we apply a hover effect on an element (like a div to have a box-shadow when hovered over) with transition of 1s. It gets an animation when hovered but as soon as u move the mouse away, it has no transition, it just drastically returns to the state.

How do you give a transition of like 1s for when we leave the hover state?

I saw a few codes but couldn't see what was making it happen.

div {
  width: 50px;
  height: 50px;
  background: purple;
}

div:hover {
  animation: nav 1s linear forwards;
}
@keyframes nav {
  to {
    box-shadow: 5px 5px 2px black;
  }
}
<div></div>

3 Answers

You shouldn't have to do anything. It will transition back when you stop hovering.

div {
  width: 50px;
  height: 50px;
  background: purple;
  transition: box-shadow 1s;
}

div:hover {
   box-shadow: 5px 5px 2px black;
}
<div></div>

I saw so a right answers above but here is another solution by JavaScript using mouseover and mouseleave events, but I notice you to use .hover, because it's simple.

div {
  width: 50px;
  height: 50px;
  background: purple;
  transition: all 1s;
}
    <div id="d"></div>
const d = document.getElementById("d");
d.addEventListener("mouseover",()=>{
   d.style.boxShadow = "5px 5px 2px black";
})
d.addEventListener("mouseleave",()=>{
   d.style.boxShadow = "0px 0px 0px";
})

Along with the other answers, you can also do something like this (non JS/jQuery):

HTML:

<div class="box">
</div>

CSS:

body {
  background: #CCC;
}
.box {
  position: relative;
  display: inline-block;
  width: 100px;
  height: 100px;
  border-radius: 5px;
  background-color: #fff;
  box-shadow: 0 1px 2px rgba(0,0,0,0.15);
  transition: all 0.3s ease-in-out;
}

/* Create the hidden pseudo-element */
/* include the shadow for the end state */
.box::after {
  content: '';
  position: absolute;
  z-index: -1;
  width: 100%;
  height: 100%;
  opacity: 0;
  border-radius: 5px;
  box-shadow: 0 5px 15px rgba(0,0,0,0.3);
  transition: opacity 0.3s ease-in-out;
}

.box:hover::after {
    opacity: 1;
}
<div class="box">
</div>

Related