Use CSS to Animate Your Background Images
I decided to start doing some front end development videos and articles, too. In this video I show you how to do background image animation of a button or link element using only CSS – no javascript.
It’s done by setting the button’s background width to 200% with background position set to top left. On hover, you set the background position to top right.
Use a css transition property to slide the image left with a timing of your choosing.
Demo Page of Background Image Animation
Here’s the entire demo page, so you can copy it and play with it yourself.
<html>
<head>
<title>scottsweb.dev - Animated Button Background</title>
</head>
<style>
/**
* scottsweb.dev
* Animated button/link background image on hover
*/
.container {
width: 500px;
height: 500px;
margin: 100px auto;
display: flex;
align-items: center;
justify-content: center;
}
.my-button {
background-color: lightblue;
border: solid 2px #000;
color: #fff;
font-size: 24px;
border-radius: 20px;
width: 300px;
height: 75px;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
background: linear-gradient(to right, blue, gray, yellow 50%, gray, blue);
background-size: 200% 100%;
background-position: top left;
transition: background-position ease 0.5s;
}
.my-button:hover {
background-position: top right;
}
</style>
<body>
<div class="container">
<button class="my-button">Hover Me</button>
</div>
</body>
</html>