Fixing CSS Jitter

The problem

While adding some swanky new buttons to my website, I decided to add a transform effect on hover to make the button go up and down like a real button.

However, transformations can be dangerous due to CSS jitter which happens when an element moves out from under your mouse and snaps back (now that it’s no longer hovered) over and over again, re-triggering the hover effect over and over again.

CSS jitter!

By the end of this post, we’ll have banished the problem to the shadow realm, and hopefully you can use this in your next (or current!) projects:

Refreshingly smooth

The solution

Here’s a codepen with a similarly styled button and hover effect (sorry mobile users, but to try these you need a device that can hover):

See the Pen ypGYBx by Jesse (@veggiedefender) on CodePen.

I’ll add a :before pseudo-element to act as a spacer, and color it red so I can see what it looks like:

 button:hover:before {
  content: '';
  box-sizing: border-box;
  position: absolute;
  top: -5px;
  left: 0;
  width: 100%;
  padding: 5px;
  background-color: red;
}

See the Pen EoGVQj by Jesse (@veggiedefender) on CodePen.

Looks good! The spacer is the same height as the transformation, so we’ve extended the element back into the mouse, meaning no more jitter! With the color removed,

See the Pen ZvVbxg by Jesse (@veggiedefender) on CodePen.