- Read Tutorial
- Watch Guide Video
Now that you understand the basics of CSS styles and selectors, let's explore more advanced options. Some of which include creating things like animations with CSS and HTML.
Before we begin, know that animations can sometimes be irritating to users, so avoid excessive use of it on any website. At the same time, animations can be a powerful tool to grab the attention of users, provided they are used sparingly and in the right context.
So, now let's see how to do animations. Open styles.css
, and go to the #heading
tag. Add an attribute called webkit-animation
(it comes with its own options). For example, let's say I want this to run infinitely, and at an interval of five seconds. So, this is the code:
#heading { padding: 42px; background-color: #e8e8e8; -webkit-animation: myAnimation 5s infinite; }
Nothing will change in the browser because I haven't defined my variables yet. To do so, add another attribute called animation
and give it the exact same value as the earlier one.
#heading { padding: 42px; background-color: #e8e8e8; -webkit-animation: myAnimation 5s infinite; animation: myAnimation 5s infinite; }
Next, I'm going to use a tool called @-webkit-keyframes
and here, I'm simply passing myAnimation
as a parameter. Here is where we'll define our animation. For example, I want the background color to change to #d3d3d3
at 50% speed.
@-webkit-keyframes 'myAnimation' { 50% { background-color: #d3d3d3; } }
Lastly, we'll add something called a @ keyframe
. This will also have the same name and code as @-webkit-keyframes
. The complete code looks like this:
#heading { padding: 42px; background-color: #e8e8e8; -webkit-animation: myAnimation 5s infinite; animation: myAnimation 5s infinite; } @-webkit-keyframes 'myAnimation' { 50% { background-color: #d3d3d3; } } @keyframes 'myAnimation' { 50% { background-color: #d3d3d3; } }
Refresh the web page, and you can see the color fading from dark grey to light grey. If you can't see it clearly, try changing the background color to something bright, though I won't recommend such a color in a real-time application.
You can try this animation with other attributes such as text, padding and just about anything else you like. Just a note here - you need CSS 3.0 or higher or animations to work.