W04 Learning Activity: CSS Animations and Transitions
Overview
CSS can animate elements without JavaScript. A transition smoothly changes a property from one value to another when an element's state changes, such as on hover. An animation runs through a series of steps you define and can repeat.
Prepare
The following explains the core CSS features used to create visual effects on web pages.
Keyframes
The @keyframes rule in CSS defines the steps of an animation, specifying how an element's styles should change over time.
You use @keyframes to create an animation by naming it and defining what should happen at different points (called keyframes) during the animation's timeline, such as at 0%, 50%, or 100%.
The following is an example of an animation for a fade in effect:
@keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
And, the following example produces a fade color effect that fades from red to yellow:
@keyframes fadeColor {
from {
background-color: red;
}
to {
background-color: yellow;
}
}
Once defined, the new keyframes animation can be referenced in an animation rule as shown below.
Animations
The animation can be defined through the animation shorthand property, or by specifying any of its sub-properties individually:
animation-name: Specifies the name of the @keyframes animation to apply to the element.animation-duration: Defines how long the animation takes to complete one cycle.animation-timing-function: Controls the speed curve of the animation, such as linear or ease-in.animation-delay: Sets how long to wait before the animation starts.animation-iteration-count: Specifies how many times the animation should repeat.animation-direction: Determines whether the animation should play forward, backward, or alternate directions.animation-fill-mode: Defines how styles are applied before and after the animation runs.animation: A shorthand property to specify several animation sub-properties all at once:
Animation shorthand properties
The following applies the fadeIn animation defined above to a box class:
.box {
animation-name: fadeIn;
animation-duration: 2s;
}
And the next example applies the fadeColor animation:
.box {
width: 150px;
height: 150px;
background-color: red;
/* Use the shorthand animation property */
animation: fadeColor 2s ease-in-out infinite alternate;
}
Transitions
Similar to the animation property, transitions can be set with individual sub-properties or all at once using the shorthand transition property.
The following transition properties are available:
transition-property: Specifies the CSS property or properties that should transition when they change.transition-duration: Defines how long the transition takes to complete.transition-timing-function: Controls the speed curve of the transition, such as ease, linear, ease-in-out.transition-delay: Sets how long to wait before starting the transition after a property change.transition: A shorthand property for all the transition properties.
The following is an example that smoothly transitions from a white background to a light blue background over 0.5 seconds when the user hovers over the box:
.box {
width: 200px;
height: 200px;
background-color: white;
border: 1px solid #ccc;
transition: background-color 0.5s ease;
}
.box:hover {
background-color: lightblue;
}
In the next example, when the user hovers over the box it will grow to 150% of its size after a slight delay with a smooth motion in and out:
.box {
width: 100px;
height: 100px;
background-color: coral;
transition: transform 0.3s ease-in-out 0.2s;
}
.box:hover {
transform: scale(1.5);
}
Prefer animating transform and opacity. Animating properties such as width and height forces the browser to recalculate the page layout on every frame.
Transform
The CSS transform property allows you to apply 2D or 3D transformations to an element.
Common transform functions include:
translate(x, y): Moves the element left/right (x) and up/down (y).rotate(angle): Rotates the element by a specified angle (for example,rotate(45deg)).scale(x, y): Resizes the element (for example,scale(1.5)makes it 150% of its original size).skew(x-angle, y-angle): Skews the element along the x or y axis.
The following is an example of a transform rule that will rotate the element 15 degrees, move it 20 pixels to the right, and enlarge it to 120% of its original size.
.box {
transform: rotate(15deg) translateX(20px) scale(1.2);
}
Advantages
There are several advantages of using CSS for animations compared to JavaScript or some other means.
- Performance: Leverages the browser's hardware acceleration, creating smoother animations and better performance.
- Ease of Use: Relatively easy to implement.
- Flexibility: Used to create a wide variety of animations.
- Browser Compatibility: Well-supported and degrades gracefully on older browsers, hopefully not breaking the user experience.
- Feedback: Provides visual cues and feedback to users.
Any visual effect should have a clear purpose and developers must consider accessibility best practices, such as ensuring animations can be paused or disabled for users who may experience motion sensitivity or have cognitive disabilities.
Users can ask their device to reduce motion. Respect that setting with the prefers-reduced-motion media query:
@media (prefers-reduced-motion: reduce) {
.box {
animation: none;
transition: none;
}
}
Activity Instructions
Build each of the following CSS animations using CodePen or by creating a simple page.
- Use the
animationshorthand,@keyframes, andtransformto create the following "loading ..." animation:Check Your Understanding
This code assumes that there is a
divwith aclassof loader..loader { position: relative; /* positions the gear relative to the loader */ margin: 2rem; width: 50px; /* width of the loader */ height: 50px; /* height of the loader */ border: 5px solid transparent; /* border width */ border-color: #999 transparent #999 transparent; /* border colors (4 - 2 transparent) */ border-radius: 50%; /* make it round */ animation: spin 1.5s linear infinite; /* spin animation with duration and continuous */ box-shadow: 0 0 1rem rgb(0 0 255 / 40%); /* blueish shadow effect on round div */ } .loader::after { content: '⚙️'; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); animation: pulse 1.5s ease-in-out infinite; } @keyframes spin { 100% {transform: rotate(360deg);} /* spin 360 degrees */ } @keyframes pulse { /* pulse the gear emoji */ 0%, 100% {transform: translate(-50%, -50%) scale(1);} /* scale to 1 */ 50% {transform: translate(-50%, -50%) scale(1.25);} /* scale to 1.25 */ } - Now improve your practice activity by using the
transitionproperty to create the following animation which activates when the user hovers over the element.Check Your Understanding
This code assumes a second
divwith a class of loader-t that has the same size, border, and::aftercontent as the loader above..loader-t { /* a transition on the transform property replaces the spin animation */ transition: transform 1.5s linear; } .loader-t::after { /* a transition replaces the pulse animation, and the gear starts hidden at scale(0) */ transform: translate(-50%, -50%) scale(0); transition: transform 1.5s ease-in-out; font-size: 2rem; } .loader-t:hover { transform: rotate(360deg); /* Rotate on hover */ } .loader-t:hover::after { transform: translate(-50%, -50%) scale(1.5); /* Scale on hover */ }Unlike animations, transitions cannot loop. They run once each time the state changes.
Test and Share
Test your updates and share your work with your peers on Microsoft Teams.
Optional Resources
- Reference: Using CSS animations – MDN
- Reference: Using CSS transitions – MDN
- Watch: Browser DevTools: Animation – A demonstration of working with animations by Web Dev Simplified.