In this post I will show you how to apply CSS animations to your webpage to create a stunning user experience.
I have been spoiled by utilizing prebuilt code blocks and templates supplied by WordPress and it's theme catalog to build webpages. It has been a log time since I styled and built a website 100% from scratch. However I have been exploring the many new features available in CSS to create more stunning websites, like using CSS animations.
CSS Animations
Applying Animations
Applying an animation to an HTML element is fairly straightforward.
element {
animation: <animation_name> <animation_timing> <duration> <iterations>
}
Keyframes
The neat thing about CSS animations is that you can set keyframes. Keyframes will allow you to control what happens at what time during the animation. Inside the keyframe, you can change various style attributes of the element you wish to animate.
Ex. If you want the animation to scale in size halfway through the animation, you would use this syntax below:
@keyframes <animation_name> {
50% { transform: scale(2.0); }
}
Also, inside the keyframe tag, you can also use a to / from keys to specify attributes to be animated.
Ex.
@keyframes <animation_name> {
from { transform: scale(1.0); }
to { transform: scale(2.0); }
}
Javascript
When you apply CSS animations to your webpage, you may want to manipulate CSS style variables. Variables in CSS can be applied like this example below.
:root {
--background-color-variable: blue;
}
Now I will show you an example of how to change the CSS variable in Javascript. This example gets the CSS variable and changes it to a random color.
var css = document.documentElement;
css.style.setProperty("--background-color-variable", "#" + Math.floor(Math.random() * 0xffffff).toString(16));
Sample
Below is a sample I created while exploring CSS animations.
This sample contains a simple DIV element that has a few animations applied to it. The document also contains a Javascript function to update a background variable color. The function is loaded using the Javascript setInterval(<function_name>, <delay>) function.
The sample contains the items covered above which are:
- setting a CSS variable
- editing CSS variable using Javascript
- 3 CSS animations applied to a DIV element
- first animation for background color change
- second animation for rotation
- third animation for scale
- animation use keyframes
Hope this was useful on exploring CSS animations.