Daya Web Logo

CSS Text Animation: Shake

Written by David Ugale
Published on 8/9/2022

Adding animation to text using CSS is quite easy using CSS animation properties.

Here's an example:

This Text Shakes. Hover Over Me!

Let's look into how this works. Here is the HTML code:

HTML

<p id="animated">
    This Text Shakes. Hover Over Me!
</p>

In this example, we are using a p tag to enclose the text that we want to animate. You can use whatever tag or element that you like, as long as you can identify it in the CSS.

Here is some basic styling for the text in our p tag:

CSS

p#animated {
    font-size: 36px;
    font-weight: bold;
    line-height: normal;
    text-align: center;
}

Here is the CSS that sets the animation for the p tag:

CSS

p#animated:hover {
    animation-name: shake;
    animation-duration: 0.5s;
    animation-iteration-count: infinite;
    cursor: pointer;
}

We add the :hover selector to activate the animation on the p tag. Consequently, whenever you put your cursor over the p tag, the animation will start.

The animation-name property is set to shake. This will be used later to identify the animation in the @keyframes rules. The animation-duration property specifies how long the animation will last. The animation-iteration-count property sets how many times the animation will run. In this example, we have set the animation to run an infinite number of times. This means that whenever you hover your mouse over the text, it will continue to "shake" indefinitely.

The @keyframes rules sets how the text will animate at certain times:

CSS

@keyframes shake {
    0% { transform: translate(1px, 1px) rotate(0deg); }
    10% { transform: translate(-1px, -2px) rotate(-1deg); }
    20% { transform: translate(-3px, 0px) rotate(1deg); }
    30% { transform: translate(3px, 2px) rotate(0deg); }
    40% { transform: translate(1px, -1px) rotate(1deg); }
    50% { transform: translate(-1px, 2px) rotate(-1deg); }
    60% { transform: translate(-3px, 1px) rotate(0deg); }
    70% { transform: translate(3px, 1px) rotate(-1deg); }
    80% { transform: translate(-1px, -1px) rotate(1deg); }
    90% { transform: translate(1px, 2px) rotate(0deg); }
    100% { transform: translate(1px, -2px) rotate(-1deg); }
}

In this example, we are using the transform property to alter the position of the element every 10% of the animation time. 0% represents the animation start while 100% represents the animation end.

Alternatively, you could use the from and to keywords to specify the animation start and end times. We decided to use the transform property in this example, but you can substitute in whatever CSS properties that you like to get your desired effect. In fact, you can change as many properties as many times as you like. And that's all there is to it to add some animation to text using CSS. Hope you found this post useful.