CSS3 transform: translate on hover, with transition

29,544

Solution 1

It's because, on the transform, you aren't hovering over the exact link anymore.

If you make the links display:inline-block you might get better results.

a {
  font-size: 2em;
  transition: transform .3s ease-out;
  display: inline-block;
}
a:hover {
  transform: translate(0, -5px);
}
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
<a href="#">Link 4</a>
<a href="#">Link 5</a>

Solution 2

This is happening because by default a elements have an inline display and the translate property can only properly affect block-level elements.

To fix this, simply give your a elements a display property set to inline-block:

a {
  display: inline-block;
  ...
}

Codepen Demo.

Share:
29,544
Brian Emilius
Author by

Brian Emilius

Library applications and content management. HTML5, CSS3, JavaScript, jQuery, AngularJS, Ajax, Bootstrap, Sass, Less, PHP, MySQL, parse.com

Updated on August 07, 2020

Comments

  • Brian Emilius
    Brian Emilius over 3 years

    This should be really simple.

    I have a bunch of anchors in my HTML, like so:

    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
    <a href="#">Link 4</a>
    <a href="#">Link 5</a>
    

    And in CSS I placed a hover effect to do a translate: transform();

    a {
      font-size: 2em;
      transition: all .3s ease-out;
    }
    
    a:hover {
      transform: translate(0, -5px);
    }
    

    Now, this should make the anchors move up 5 pixels when you hover them. And they do, but they snap down immediately, even though the mouse still hovers. Anyone else encountered this behavior and found a solution? I'd like the effect to stay active while mouse hovers. Codepen link: http://codepen.io/BrianEmilius/pen/NqoLQo