CSS Animations allow creating some complex animations on the website without using old fashioned Flash animations.
In this tutorial, I am just using a straightforward animation that shows a boy running on the road. But once you see the code, there is only one simple city background image moving using the CSS3 animation.
And boy runner is a simple gif animation. I will link all these assets in this post.
The HTML code for this CSS animation scene is below. You need to create one HTML file in your working directory—e.g index.html.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Runing</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="moving-bg">
<img src="runner.gif" alt="" class="runner">
</div>
</body>
</html>
You can see nothing fancy but a div with class “moving-bg” and a gif in an image tag. The gif image is here.
Now you need to create one stylesheet file for all the CSS, e.g. style.css. You can even put this CSS in the head section of the HTML file. But I want to keep the code clean.
body{
margin:0;
padding:0;
}
.moving-bg{
background: url(bg.jpg) repeat-x #87CEFA;
background-position: 0 0;
background-size: cover;
height: 100vh;
margin: 0;
padding: 0;
position: relative;
animation: animateX 15s linear infinite;
}
@keyframes animateX{
from{
background-position: 0 0;
}
to {
background-position: 100% 0;
}
}
.runner{
position: absolute;
bottom:0;
height: 45%;
}
You can see, the stylesheet is not very complex. Most of the CSS rules are very simple.
In the “.moving-bg” class rule, I used the background, which will repeat on the x-axis, and the “background-position” is 0 0, which is the actual top left on the screen. Also, the background will cover the whole size of the view area, which you can see is 100vh in the height property.
The main property is animation. It is changing “background-position” from 0 to 100% as defined in the @keyframes. You can read more about CSS3 animation at w3schools.
Now see the final output and it is pretty satisfying. https://youtu.be/AJir-LgXrWA