Animation CSS Series: Bouncy Ball Part 2

Photo by Cookie the Pom on Unsplash

In the second part in this series we will be looking at making the bouncing look more realistic. We are going to be doing this by doing two different things. If you want to see the initial setup code check out my first blog:

We ended up with a bouncy ball looking like this:

Bouncy Ball

and our code looked like this:

Starting CSS and HTML

Firstly, we are going to make it replicate bouncing a bit more. Each time it bounces, the height of the bounce will decrease and it will go up slower than it falls. Let’s adjust our keyframe to allow for multiple steps rather then just “from” and “to”.

So remove the “to” and “from ” from the keyframe and we are going to replace it with percentages. This breaks up the time that the animation plays for into different intervals. As you can every second interval we set top to 0px which means it hits the floor and the alternative intervals are decreasing in the amount of px it rises from the bottom by each time.

Keyframe example

Next we are going to need to adjust it so it bounces on the line and we are also going to want to increase the speed so the animation runs over a longer time.


Now you should have something like this.

Bouncy ball

Secondly we are going to make it to look a bit more dynamic when it bounces.

An important principle on making animations look realistic is called “stretch and squash”. This means when something you are animating hits another object such as a floor, it’s height decreases and the width increases. You can read more about this in the blog by CSS Animation

The way we are going to do this is by changing the width and the height every time the keyframe is at “bottom: 0px; ”.

Like this:

Keyframe example

I also need to change the margin top for the .ball, so it hit the line each time so I changed it to margin-top: 210px;

You should now get something like this:

Bouncy ball

As you can see the ball stays squashed because we never change the width and the height back to what it was originally.

So let’s add in some additional intervals in the keyframe to change it back.

Keyframe example

I also added smaller width and height changes towards the end because in reality the force it would be hitting the floor would be smaller so it wouldn’t change as much, but you can play around and see what works for you.

You should get an end product looking like this:

Final Bouncy ball

And here is the code for it.

Final HTML and CSS

I would love to hear your suggestions on improvements and stay tune for part 3 where we add the last few changes to give it a 3d effect.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store