Animate Cheaply and Respect Reduced Motion

In the last lesson, Animate Changes With Transitions, the nav links and the Sign up button learned to fade both ways because their transition sits on their own rules. Rosa would like two more touches: the event cards on the events page should lift when a visitor points at them, and the Free badges in the plots table should catch the eye when the page opens.

In this lesson, you’ll pick properties that animate without redoing the page’s layout, write a keyframe animation, and turn motion down for visitors who ask for less. Start with the cards and choose which property should move them.

Lift the Cards Without Moving the Page

You could make a card grow with width or nudge it up with margin-top. However, not every property costs the same to animate. Watch out: width, height, and margin feed into layout, so animating them can make the browser work out the size and position of boxes again on every frame.

Whether the neighbors move as well depends on the layout around the card. In a row with room to spare, a wider card pushes the next one along.

Say three cards sit in a flex row with a fixed 1rem gap, packed at the start. There’s room for them to grow, so no card shrinks.

You make the middle card grow on hover from width: 10rem to 20rem, with a one-second linear transition. With the usual 16-pixel root font size, the card to its right has moved 80 pixels halfway through, and it keeps moving until the growth ends. Make the same card grow with transform: scale(1.5) instead, and its neighbor doesn’t move at all. The card grows over it.

Try both in the widget below. Pick width or transform, then drag the time slider through the one-second hover:

Interactive diagram — enable JavaScript to view.

With width, the right card is 80 pixels along at 0.50 seconds and keeps going to 160. With transform, it never moves, because the middle card’s layout width stays at 160 pixels while its drawing grows over both neighbors.

The transform property moves, scales, or rotates an element’s drawing with functions such as translateY(), scale(), and rotate(). The browser applies it after layout, so the element’s space in the page stays where it was. The same goes for opacity, which fades an element from 1, fully visible, to 0, invisible. That’s why these two are the cheap ones to animate. Animate a layout property such as width only when the neighbors really must move.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.