Bouncing Ball With CSS
Roland Taylor
Posted on October 5, 2021
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.
This time around, I'll just jump straight to the code.
Our HTML Code:
<div>
</div>
<span>
</span>
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;
}
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;
}
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%;
}
}
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%);
}
}
You can find the source code for this short tutorial here: https://codepen.io/rolandixor/pen/mdwZReq
Posted on October 5, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.