Sub topic 1
Transitions or Animations: Choosing the Right Tool
Prerequisites
This chapter assumes basic CSS selectors, the cascade, common properties such as color and opacity, :hover, :focus-visible, HTML, and JavaScript class changes.
Transitions or Animations: Choosing the Right Tool
A transition interpolates a property between its current value and a new value after a state change. Use it for interaction feedback, such as a button changing color when focused.
A keyframe animation describes several stages and can run automatically, repeat, reverse, or pause. Use it for effects such as a loading indicator or an element entering the page.
Writing a Transition
The transition shorthand combines the property, duration, timing function, and delay:
.button {
background-color: #2563eb;
transform: translateY(0);
transition: background-color 200ms ease-out, transform 200ms ease-out;
}
.button:hover,
.button:focus-visible {
background-color: #1d4ed8;
transform: translateY(-2px);
}Here, 200ms is the duration. ease-out controls the rate of change. A delay can be added after it, such as opacity 300ms linear 100ms. Longhand properties include transition-property, transition-duration, transition-timing-function, and transition-delay.
Easing and Interpolation
An easing function controls how quickly a transition progresses. ease is a general-purpose curve. cubic-bezier() lets you define a custom curve. steps(4) changes values in four jumps instead of smoothly, which suits a frame-like effect.
The browser interpolates compatible values between endpoints. For example, it can calculate intermediate colors, lengths, opacity values, and transform functions. Some values, such as display: none and display: block, are discrete and do not smoothly interpolate.
Triggering Transitions
A transition starts when a matched rule changes the transitioned property. Common triggers include :hover, :focus-visible, and a class added by JavaScript. Keep the transition on the base rule so it works both when the state begins and when it ends.
Animate transform and opacity when possible. They usually avoid the layout work caused by changing dimensions or position properties.
Exercise
Which tool fits a card that moves from its original position to a highlighted position when a class named selected is added?
Show answer
Use a transition on the base card rule, with .card.selected changing transform or another compatible property.