Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a CSS transition work "backwards"?

So I have this transition on hover, that makes a border at the bottom of the element that is being hovered over. All is well there, but when the mouse leaves the element, the border simply disappears, while I want it to "retract" back again. Codepen

HTML:

<div class="object">

<p>Object</p>

</div>

CSS:

* {
background-color: #222;
color: white;
font-family: sans-serif;
font-size: 30pt;
}

p {
 width: 200px;
height: 100%;
margin-top: 70px;
text-align: center;
transition: 0.2s border-bottom;
-webkit-transition: 0.2s border-bottom;
margin: auto;
margin-top: 50px;
}

p:hover {
  border-bottom: 5px solid white;
}

How would I go about doing this, as simple as possible? Thank you ;3

like image 282
S. E. Avatar asked Apr 20 '15 21:04

S. E.


People also ask

How do you add a reverse transition in CSS?

“css transition reverse” Code Answer's (1) normal : forward direction, this is the default value. (2) reverse : the animation sets in the reverse direction ( backward ). (3) alternate : the animation plays normal first and then reverse. (4) alternate-reverse: the animation plays reverse first and then normal.

How do I enable transition CSS?

To trigger an element's transition, toggle a class name on that element that triggers it. To pause an element's transition, use getComputedStyle and getPropertyValue at the point in the transition you want to pause it. Then set those CSS properties of that element equal to those values you just got.

Which CSS property is used for transition effect?

The transition-property property specifies the name of the CSS property the transition effect is for (the transition effect will start when the specified CSS property changes). Tip: A transition effect could typically occur when a user hover over an element.


2 Answers

Transitions work in both directions automatically.

The problem you are experiencing is that border-style is not a property that can be animated so it changes instantly.

This means that when you hover it, it becomes solid instantly and then spends time becoming 5px.

But when you unhover it, it becomes none instantly and you can't see the width animating.

Make the default (non-hovered) state explicit so that the border-width is the only thing that changes when you hover it.

Add:

border-bottom: 0px solid white;

to the rules for p.

like image 51
Quentin Avatar answered Oct 11 '22 03:10

Quentin


I don't know if this could help, but in my case I just did like this:

Over:

.<nameOfClass>:hover{
 transition: width 0.4s ease-in-out;
}

No over:

.<nameOfClass>:not(:hover){
 transition: width 0.4s ease-in-out;
}
like image 27
Saul Kevin Silva Avatar answered Oct 11 '22 03:10

Saul Kevin Silva