CSS Animations
Yong Jun, Talk CSS, 29 Feb 2016
Why use CSS animation?
No JavaScript
- No <canvas>
- No DOM manipulation
- No window.requestAnimationFrame( )
Better performance
- Hardware accelerated
- Handled by GPU
- Less jank
How to apply CSS animation?
transition
- Fire once and forget
- Have to be triggered
- Based on interpolation
animation
- Loopable
- Triggered on load
- Based on keyframes
transition syntax
element {
property: some_value
transition: property duration timing_function
}
animation syntax
element {
animation: keyframe_name duration timing_function
delay iteration direction
}
@keyframe keyframe_name {
from { property: initial_value }
50% { property: intermediate_value }
to { property: final_value }
}
How to trigger a transition?
- JavaScript
- CSS
- toggleClass
eg. setTimeout(function () {
element.style.property = new_value
}, 500)
eg. :hover :focus :checked :valid
CSS:
element.changed {
property: new_value
}
JS:
element.classList.toggleClass('changed')
More on timing function
Animating more than one properties
element {
transition_: property_1 1s, property_2 1s;
}
or
element {
transition-property: property_1, property_2;
transition-duration: 1s;
}
@keyframes keyframe_name {
50% {
property: value_1;
animation-timing-function: ease-in;
}
100% {
property: value_2;
animation-timing-function: ease-out;
}
}
Using CSS transform together with CSS animation
Let GPU handles your transitions / animations
- Layout
- Paint
- Composition
- Opacity
- Transform
- Filter
Common issues
-
Transformation overwritten
- transform is a single property
- can only be applied once
-
Doesn't come out as what I expected
- Order of transformation?
- Have you set your transfom-origin correctly?
-
What if I want to apply separate animations to two different transformation?
- Wrap element in an outer div and apply transformation separately
Wrong:
element {
transform: scale(2);
transform: rotate(30deg);
}
Right:
element {
transform: scale(2) rotate(30deg)
}
Transition / Animation event
Syntax
element.addEventListener('transitionend', callback)
element.addEventListener('animationend', callback)
Multiple animating elements
var async = require('async')
async.each(array_of_elem, function(element, cb) {
// attach transitionend listener
element.addEventListener('transitionend', function (event) { cb(null) })
// trigger transition
element.style.property = new_value
}, final_callback_function)
CSS Animation
By yongjun21
CSS Animation
- 1,679