Home > OS >  How to make a fadeout animation when the mouse leaves?
How to make a fadeout animation when the mouse leaves?

Time:07-15

I have made the fade in animation when the mouse enters a div. But I am not able to make the fade out animation when the mouse leaves. This is my code:

<div>abcd: </div>

div::after {
    content: "The Breast Pocket was once used mostly to hold handkerchiefs, but generally has moved on to the functionality to hold pocket squares. Pocket squares are our primary accessory to add and show off a great tie.";
    display: none;
    background:  rgba(23,23,90,0.8);
    color: white;
    padding: 15px;
    border: 1px solid grey;
    border-radius: 10px;
    animation-name: out;
    animation-duration: 1s;
}

div:hover::after {
    display: block;
    position: absolute;
    margin-right: 26px;
    margin-left: 10px;
    animation-name: in;
    animation-duration: 1s;
}

@keyframes in
{
 0% { opacity: 0;  }
 100% { opacity: 1; }
}

@keyframes out
{
 from { opacity: 1; }
 to { opacity: 0; }
}

And this is the codepen: https://codepen.io/boidurja-talukdar/pen/bGvBjrR

CodePudding user response:

did you try this code ? i have some changed on css code.

div::after {
        content: "The Breast Pocket was once used mostly to hold handkerchiefs, but generally has moved on to the functionality to hold pocket squares. Pocket squares are our primary accessory to add and show off a great tie.";
        background:  rgba(23,23,90,0.8);
        color: #fff;
        padding: 15px;
        border: 1px solid grey;
        border-radius: 10px;  
        position: absolute;
        margin-right: 26px;
        margin-left: 10px;
        opacity: 0;
        transition: all 1s;
}

div:hover::after {
        opacity: 1;
}
<div>abcd: </div>

CodePudding user response:

If you use transition rather than animation the info will automatically fade out on the hover being removed.

A few other things had to alter here. The info is 'there' all the time in an absolutely positioned element but with opacity 0. The margins are set rather than being introduced on the hover. This is because you otherwise will get 'flashing' as the after element moved under the cursor on a hover, the cursor will hover/not hover/hover as the margins are reset if hovered on the left hand side.

div::after {
  content: "The Breast Pocket was once used mostly to hold handkerchiefs, but generally has moved on to the functionality to hold pocket squares. Pocket squares are our primary accessory to add and show off a great tie.";
  background: rgba(23, 23, 90, 0.8);
  color: white;
  padding: 15px;
  border: 1px solid grey;
  border-radius: 10px;
  transition: opacity 1s;
  display: block;
  position: absolute;
  opacity: 0;
  margin-right: 26px;
  margin-left: 10px;
  z-index: 1;
}

div:hover::after {
  opacity: 1;
}
<div>abcd: </div>

  •  Tags:  
  • css
  • Related