6

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

Brian Emilius
  • 717
  • 1
  • 8
  • 31

2 Answers2

18

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>
Paulie_D
  • 107,962
  • 13
  • 142
  • 161
  • Beat me to it. Also, don't forget about vendor specific. Codepen: http://codepen.io/anon/pen/waNYKN – Josh Salazar Aug 06 '15 at 15:53
  • Yup, this did it! Thought it would be a simple solution :) @JoshSalazar yeah codepen doesn'tneed the vendor prefixes in most cases, but they're in my project code. – Brian Emilius Aug 06 '15 at 15:55
  • Actually it doesn't seem to be because of the hit area. If you look at the second snippet in the answer that I linked you would see that the same behavior happens even when you do `body:hover`. It seems more to do with the accelerated rendering process. The solution however is still the same :) – Harry Aug 06 '15 at 16:01
  • 1
    @Harry Yeah...I see you found the right dupe target. I've removed that part. – Paulie_D Aug 06 '15 at 16:02
3

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.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218