10

How I can change the background-color on a:hover using a transition from the bottom to the top with a duration of 0.3s?

<ul>
  <li><a></a></li>
  <li><a></a></li>
  <li><a></a></li>
</ul>

Is that possible?

Thanks

Zach Saucier
  • 24,871
  • 12
  • 85
  • 147
user1878413
  • 1,813
  • 4
  • 18
  • 24

1 Answers1

17

There is no way to (generically) apply a transition direction in CSS. However, we can work around that limitation by using a pseudo element (or other method like how this example uses gradients).

By using a pseudo element, which initially has a visible height of 0, we can transition the height from and to a desired direction when the link is hovered. It's best to use transform: scale for performance reasons, which means that we need to set our transform-origin to bottom center in this case to make sure it goes from bottom to top.

This approach is probably the most general, working with non-solid backgrounds and such, but does require a pseudo element or child element.

The CSS for that approach would be:

li {
    background: red;
}
a {
    position: relative;
    z-index: 1;
}
a::after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 100%;
    transform: scaleY(0);
    transform-origin: bottom center;
    background: blue;
    z-index: -1;
    transition: transform 0.3s;
}
a:hover::after {
    transform: scaleY(1);
}

Demo

Zach Saucier
  • 24,871
  • 12
  • 85
  • 147
  • The pseudo element :after did worked for me with your DEMO. Thx – Patrice Poliquin Nov 26 '14 at 16:21
  • Perhaps the first line in the answer is now false simply because of browser improvements, but this codepen example proves that it's false to say that there's no way to apply a transition direction: https://codepen.io/brandon4117/pen/ihIgE – shellscape Aug 23 '16 at 14:27
  • @shellscape No, the statement is still true. You can change the transform origin and transition an *element* in that way using transforms, but you cannot apply a transition direction by itself. For example, you cannot transition the opacity of an element from left to right without faking it (which is what your example does by using gradients) – Zach Saucier Aug 23 '16 at 14:48
  • If you replace that blue background with an image, you will see my point. It only works because the background color is solid using that method – Zach Saucier Aug 23 '16 at 14:49