Create a “Slot Machine” Hover Effect with CSS

A client requested a “slot machine” hover effect for their social network buttons.  When you hover on the icon, it moves up, sort of like in a slot machine, and changes color.  Here’s an example of what I’m talking about:

It turns out that this effect can be accomplished with some clever CSS!  No JavaScript required!

The key to this effect is to use CSS transitions to animate the background-position of the background-image.

How To Do It

First, create a div to contain the button.   Let’s call it “#button”.

Next, here is the CSS for the button in normal state, and in hover:

#button {
background-image: url('icon-fb-hover.png');
background-attachment:local;
background-position: 0 0;
background-repeat: repeat-y;
height: 48px;
width: 46px;
transition: background 0.2s ease-in-out;
-moz-transition: background 0.2s ease-in-out;
-webkit-transition: background 0.2s ease-in-out;
border: 1px solid blue;
}

#button:hover {
background-position: 0 -48px;
border: 1px solid red;
background-color: pink;
cursor: pointer;
}

The image that you want to animate will be displayed as the background image of the div.  Be sure to have the “background-attachment:local;” there or else it won’t work properly.  The “transition” CSS tells the browser to animate the background in 0.2 seconds using a particular easing curve.

In the hover state, the key is to specify a new background position for the image.  Since it is repeated in the y-direction, it merely reappears in its original position when I specify -48 pixels (which is the height of the image) in the y-direction.  If you want, however, you can supply a different image below the main image and it will rotate up when you hover instead.

The border and background color can be anything you want.

Hope this was helpful! – Brian

Featured Image Photo by Hello I’m Nik on Unsplash

Shares

Discover more from Web Developer Tips and Tricks

Subscribe to get the latest posts sent to your email.

Please Leave a Question or Comment

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Inline Feedbacks
View all comments
Steve
Steve
7 years ago

Hey i have been playing around the with the css. it works. but my problem is, i want to apply the same effect into the main menu button (top menu)

heres a reference website that you can refer to

https://johnnycupcakes.com/

hope you can assist me in this matter, is it possible to achieve it using ONLY CSS?

Thanks

Brian Shim
Brian Shim
7 years ago
Reply to  Steve

HI Steve,

You would have to change your main logo to be a background image in order to use the CSS that I have here. I suggest using a transparent PNG file for the image as a placeholder to accomplish this.

Best,
Brian