Different CSS Animations on Hover In and Out

July 7, 2017

Recently a client requested a hover effect on a site’s buttons that slide in from the left and out to the right. I know that jQuery has a hover function that can apply different functions on in and out, however I’m reluctant to use this as iOS devices sometimes interpret the function as a 2 part touch sequence, and it’s a little heavy compared to a small css property. Additionally I planned to use a pseudo element to show the transition, which isn’t directly selectable by jQuery. After some tinkering, here’s the result:

Button Text

The solution is to apply the transition property to only the transform property, rather than all which I did by default. Since the transform-origin no longer has the transition applied to it, the positioning changes from right to left instantly on hover while the transform takes longer.

a.button {
  display: inline-block;
  position: relative;
  z-index: 1;
  color: #f87d33;
  background: transparent;
  font-size: 16px;
  line-height: 35px;
  padding: 0 10px;
  border: 1px solid #f87d33;
  -webkit-transition: all 0.4s ease;
  transition: all 0.4s ease;
}
a.button:before {
  display: block;
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: -1;
  background: #f87d33;
  /* transition on the specific property, lots of browser prefixing */
  -webkit-transition: -webkit-transform 0.4s ease;
  transition: -webkit-transform 0.4s ease;
  transition: transform 0.4s ease;
  transition: transform 0.4s ease, -webkit-transform 0.4s ease;
  /* transform scale */
  -webkit-transform: scale(0, 1);
  -ms-transform: scale(0, 1);
  transform: scale(0, 1);
  /* transform origin */
  -webkit-transform-origin: right center;
  -ms-transform-origin: right center;
  transform-origin: right center;
}
a.button:hover {
  color: #fff;
}
a.button:hover:before {
  /* transform scale */
  -webkit-transform: scale(1, 1);
  -ms-transform: scale(1, 1);
  transform: scale(1, 1);
  /* transform origin */
  -webkit-transform-origin: left center;
  -ms-transform-origin: left center;
  transform-origin: left center;
}

I just used this for a scale property, but by implementing targeted transitions it opens the doors to some pretty interesting animations moving forward.

Good luck!

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive