×
By the end of this chapter, you should be able to:
transform
property in CSStransition
property to perform simple animation effects without using JavaScriptLike transforms, CSS transitions are another newer technology, which allow us to perform animations without using JavaScript! While JavaScript is great for more complex animations, for simple things CSS animations can achieve the same effect. There are many opinions about when you should use a CSS animation versus a JavaScript animation; if you'd like to read more about the debate, check out this article.
CSS transitions are set using the transition
property. They provide a way to set and control animation speed when changing CSS properties. Instead of having property changes take effect immediately, you can cause the changes in a property to take place over a period of time. For example, if you change the color of an element from white to black, usually the change is instantaneous. With CSS transitions enabled, changes occur at time intervals that follow an acceleration curve, all of which can be customized. You can read more about them here.
CSS transitions let you decide which properties to animate (by listing them explicitly), when the animation will start (by setting a delay), how long the transition will last (by setting a duration), and how the transition will run (by defining a timing function, e.g. linearly, or quick at the beginning and slow at the end). You can also set transitions for multiple properties by comma separating values in the transition
property. Let's take a look at an example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" href="style.css"> </head> <body> <a href="">Click me!</a> </body> </html>
style.css
a { background-color: #139CFF; text-decoration: none; color:white; padding: 10px; border-radius: 7px; display: inline-block; font-family: helvetica; /* transition: <property> (default all) <duration> <timing-function> (default ease) <delay> (default 0); */ transition: background-color .5s, color .5s linear, border-radius 2s ease-out; /* try playing around with the parameters in the value and see how the transition changes! */ } a:hover { background-color: #35EC5C; color: black; border-radius: 30px; }
When you open up this page in Chrome and hover over the button, you should see a nice, smooth transition:
If you comment out the transition
rule in the CSS, however, the change in style will be much more abrubt:
Notice that if you put the transition
property on a:hover
instead of a
, the transition will occur when you mouse into the button, but not when you mouse out!
Fore more on CSS transitions, check out this CSS Tricks article.
When you're ready, move on to CSS Animations