- slide an element across the screen
- make an element fade in or out
- interpolate between two colors
- spin or scale an element
...and much more. Most CSS properties can be animated — even 3D transforms — so there's a tremendous number of combinations possible to create unique effects.
Code-wise, there are two components needed to define and execute a CSS Transition:
- A definition for the transition (which includes things like how long it will take), written in CSS.
Once you've defined your transition in CSS (part 1 above), the web browser will take care of rendering all the frames of the transition animation when a computed style change occurs (part 2). Besides specifying how long the transition will take, you can also define what sort of timing function will be used (ease, linear, etc.). It's also possible to transition several CSS properties at once.
Before digging into all the details of CSS Transitions in later sections of this chapter, let's go over the basics with a simple example. Let's say that you want to make an element disappear when it's clicked, and to do that you're going to change the element's opacity. Listen for an event on the element ( such as click, mousedown, or mouseup), and change the value of the opacity property from 1 to 0 when the event is emitted:
With this code in place, the element will disappear immediately when clicked. To cause the element to fade out slowly over time, use CSS to define a CSS transition.
For example, if you want the box to fade out uniformly over a period of 3 seconds, add this CSS:
This code sample introduces three CSS properties for defining CSS transitions: transition-property, transition-duration, and transition-timing-function. You'll learn all the details for these properties in the next section called Defining Transitions, and in later sections of this book you'll learn how to:
- transition multiple CSS properties at once
- trigger transitions to begin in different ways
- reverse a transition
- define your own timing functions
- chain transitions together
- $7.99 - Download now