Sub topic 2
Moving, Scaling and Rotating with `transform`
Assume you know CSS selectors, the cascade, common properties, and how JavaScript can toggle a class. This chapter uses those skills to create multi-step motion.
Moving, scaling and rotating with `transform`
The transform property changes an element’s visual position, size, or angle without changing the layout of nearby elements.
translateX()andtranslateY()move an element.scale()changes its size.rotate()turns it around its transform origin.- Multiple functions can be combined in one value.
.card {
transform: translateY(0) scale(1) rotate(0deg);
transition: transform 200ms ease-out;
}
.card:hover {
transform: translateY(-8px) scale(1.03) rotate(1deg);
}The browser interpolates between the starting and ending transform values. transform-origin: center is the default. Set it explicitly when rotation or scaling should use another point.
Describing multi-step motion with `@keyframes`
A transition describes two states. An animation can describe several stages with @keyframes.
@keyframes float {
0% {
transform: translateY(0) rotate(0deg);
}
50% {
transform: translateY(-12px) rotate(2deg);
}
100% {
transform: translateY(0) rotate(0deg);
}
}Controlling animation timing and repetition
The animation shorthand combines the animation name, duration, timing function, delay, repetition count, direction, and fill mode.
.badge {
animation: float 1.5s ease-in-out 200ms 3 alternate both;
}This animation waits 200 milliseconds, runs for 1.5 seconds per cycle, repeats three times, and reverses direction on alternating cycles. infinite replaces 3 when the animation should continue indefinitely.
Individual properties can make the behavior clearer:
.badge {
animation-name: float;
animation-duration: 1.5s;
animation-iteration-count: infinite;
animation-delay: 200ms;
}Fill mode, direction, and pausing
animation-fill-mode: both applies the first keyframe during the delay and keeps the final keyframe after the animation ends. Other useful values are forwards, backwards, and none.
Use animation-direction: reverse to play keyframes backward, or alternate to switch direction each cycle. Pause a running animation with:
.badge.is-paused {
animation-play-state: paused;
}Exercise
Which declaration pauses an animation without removing its current visual position?
Show answer
animation-play-state: paused;