Coding: Creating a Simple Animation
An animation on a web page is not a video. Nothing was filmed. You tell the browser where something should be at the start, where it should be in the middle, and where it should end — and the browser works out every position in between, sixty times a second.
That instruction is called a keyframe, and you only ever write the corners.
- A text editor (Notepad on Windows, TextEdit on a Mac)
- A web browser
The Code
<!DOCTYPE html>
<html>
<head>
<title>Bouncing Ball</title>
<style>
#ball {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: red;
position: relative;
animation-name: bounce;
animation-duration: 2s;
animation-iteration-count: infinite;
}
@keyframes bounce {
0% {top: 0px;}
50% {top: 200px;}
100% {top: 0px;}
}
</style>
</head>
<body>
<div id="ball"></div>
</body>
</html>
- Open your text editor and start a new file.
- Type the code above.
- Save it as bouncing_ball.html — the
.htmlending is what makes it a web page. - Drag the saved file into your browser. A red ball bounces, and keeps bouncing.
Reading the Keyframes
The three lines inside @keyframes bounce are the whole animation:
0%— at the start,top: 0px. The ball sits where it was drawn.50%— halfway through,top: 200px. It has moved 200 pixels down.100%— at the end, back totop: 0px. It has returned.
The browser fills in everything between those three moments. You never wrote "move down a bit" — you wrote where it should be, and the movement is what that looks like from outside.
Because animation-duration is 2s, the whole down-and-up takes two seconds.
Because animation-iteration-count is infinite, it starts again immediately.
Change the 200 and Watch
The 200px on the 50% line is the lowest point of the bounce. Drag the
slider to see what different values do to it.
The dashed line is the ball's starting position at 0% and 100%. The solid
ball is where it gets to at 50%. Set the slider to 0 and the two keyframes
match, so nothing appears to happen at all — the ball animates from where it
is, to where it is.
The keyframes put the ball at top 0px at 0%, and at top 200px at 50%. The whole bounce takes 2 seconds. When is the ball at its lowest?
- Straight away, at the very start
- After 1 second, halfway through
- After 2 seconds, at the end
Make It Yours
- Change
background-color: redto any color name you like. - Change
animation-durationfrom2sto0.5s, then to6s. - Change
widthandheighttogether to resize the ball. Change only one of them and it stops being a circle —border-radius: 50%gives you an oval.
Save and reload after each change. The bounce you get is the direct result of numbers you can see and edit, which is the whole reason this is coding and not a video.