DEV Community

Roland Taylor
Roland Taylor

Posted on

Bouncing Ball With CSS

What's up?

Have you ever wanted to bounce a ball with CSS for no apparent reason? Well, in this tutorial, I will show you how to do just that. You'll also learn CSS animations along the way.

A bouncing ball, made with CSS

This time around, I'll just jump straight to the code.

Our HTML Code:

<div>
</div>

<span>
</span>
Enter fullscreen mode Exit fullscreen mode

All we need is a div and a span. The div will act as our ball, and the span will act as a shadow. Both will be animated, but we'll get to that when we jump into the CSS code.


NB: We could literally use almost any element for this purpose. I just choose two that are quick and easy to remember.


Our CSS Code:

To style the ball, we have:

div {
  background-color: red;
  border-radius: 100%;
  height: 50px;
  left: calc(50% - 50px);
  position: absolute;
  right: calc(50% - 50px);
  width: 50px;
  animation: bounce 1s ease-in-out infinite;
  animation-fill-mode: both;
  animation-direction: alternate;
}
Enter fullscreen mode Exit fullscreen mode

And to create the shadow, we use:

span {
  border-radius: 100%;
  bottom: 32.5%;
  left: calc(50% - 50px);
  right: calc(50% - 50px);
  position: absolute;
  content: '';
  background-color: black;
  filter: blur(3px);
  width: 50px;
  height: 5px;
  animation: shadow 1s ease-in-out infinite;
  animation-fill-mode: both;
  animation-direction: alternate;
  z-index: -1;
}
Enter fullscreen mode Exit fullscreen mode

Our ball is animated via this declaration block, for the animation we're calling 'bounce':


@keyframes bounce {
  from {
    top: 25%;
    transform: scaleX(79.5%) scaleY(65%);
  }
  to {
    top: 55%;
  }
}
Enter fullscreen mode Exit fullscreen mode

NB: You can tweak these property values any way you like. What's important here is the top: property, which does the bouncing for us, by moving the ball up and down the page. If you like, you can swap these values and see what it does.


Finally, here is the declaration block for the animation, 'shadow'. Again, you can tweak these values any way you like, and see what happens.

@keyframes shadow {
  from {
    opacity: 0;
    transform: scale(0);
  }
  to {
    opacity: .5;
    transform: scale(100%);
  }
}
Enter fullscreen mode Exit fullscreen mode

You can find the source code for this short tutorial here: https://codepen.io/rolandixor/pen/mdwZReq

Top comments (4)

Collapse
 
eraz7 profile image
Erfan Azary • Edited

This may look more natural:

codepen.io/eraz7-the-selector/pen/...

Image description

Collapse
 
rolandixor profile image
Roland Taylor

Hi Erfan, the goal of this tutorial was to simulate a ball that squishes on bounce, not just the movement of the ball.

Collapse
 
eraz7 profile image
Erfan Azary

Thanks for the tutorial Roland, good luck

Thread Thread
 
rolandixor profile image
Roland Taylor

You're welcome 🙏