The Art of Transition Unique Transition Sweep Fx
Introduction
The world of web animations has become a sprawling jungle of tools and technologies. Libraries like GSAP and Framer Motion and React Leap have sprung up to help u.s. add motion to the DOM.
The most key and critical slice, though, is the humble CSS transition. It's the first animation tool that most front-end devs larn, and it's a workhorse. Even the most grizzled, weathered animation veterans withal reach for this tool ofttimes.
There's a surprising amount of depth to this topic. In this tutorial, we'll dig in and learn a bit more about CSS transitions, and how nosotros can use them to create lush, polished animations.
Link to this heading
The fundamentalsThe main ingredient nosotros need to create an animation is some CSS that changes.
Hither's an example of a button that moves on hover, without animating:
Code Playground
This snippet uses the :hover
pseudoclass to specify an additional CSS declaration when the user'southward mouse rests atop our button, like to an onMouseEnter
event in JavaScript.
To shift the element upwardly, we employ transform: translateY(-10px)
. While we could take used margin-meridian
for this, transform: translate
is a better tool for the job. We'll run into why after.
Past default, changes in CSS happen instantaneously. In the glimmer of an eye, our push has teleported to a new position! This is incongruous with the natural world, where things happen gradually.
Nosotros can instruct the browser to interpolate from i state to some other with the aptly-named transition
property:
Lawmaking Playground
transition
can take a number of values, simply only two are required:
-
The proper name of the belongings we wish to animate
-
The duration of the animation
If yous plan on animating multiple properties, y'all can pass it a comma-separated listing:
Link to this heading
Timing functionsWhen nosotros tell an chemical element to transition from one position to another, the browser needs to work out what each "intermediary" frame should look like.
For example: let's say that nosotros're moving an chemical element from left to right, over a 1-second duration. A smooth blitheness should run at 60fps, which means we'll need to come up with 60 individual positions betwixt the start and end.
Let's first by having them be evenly-spaced:
Click me!
To clarify what's going on here: each faded circle represents a moment in fourth dimension. As the circle moves from left to right, these are the frames that were shown to the user. It's like a flipbook.
In this animation, we're using a linear timing function. This ways that the element moves at a constant step; our circumvolve moves by the same amount each frame.
There are several timing functions available to us in CSS. We can specify which 1 we want to use with the transition-timing-office
property:
Or, we can laissez passer it directly to the transition
shorthand property:
linear
is rarely the best selection — after all, pretty much nix in the existent world moves this way. Adept animations mimic the natural world, so we should pick something more organic!
Allow's run through our options.
Link to this heading
ease-out ease-out
comes charging in like a wild balderdash, but it runs out of energy. Past the cease, it'south pootering forth like a sleepy turtle.
Attempt scrubbing with the timeline; detect how desperate the movement is in the offset few frames, and how subtle it becomes towards the end.
If nosotros were to graph the deportation of the element over fourth dimension, it'd await something like this:
When would you lot use ease-out
? It's most ordinarily used when something is entering from off-screen (eg. a modal actualization). It produces the consequence that something came hustling in from far abroad, and settles in front of the user.
Link to this heading
ease-in ease-in
, unsurprisingly, is the contrary of ease-out
. It starts slow and speeds up:
As nosotros saw, ease-out
is useful for things that enter into view from offscreen. ease-in
, naturally, is useful for the opposite: moving something beyond the bounds of the viewport.
This combo is useful when something is entering and exiting the viewport, similar a modal. We'll look at how to mix and match timing functions shortly.
Note that ease-in
is pretty much exclusively useful for animations that cease with the element offscreen or invisible; otherwise, the sudden stop tin be jarring.
Link to this heading
ease-in-outAdjacent up, ease-in-out
. It'south the combination of the previous two timing functions:
This timing function is symmetrical. It has an equal amount of acceleration and deceleration.
I find this curve most useful for anything that happens in a loop (eg. an element fading in and out, over and over).
It's a big footstep-up over linear
, but before you go slapping information technology on everything, let'south look at one more selection.
Link to this heading
easeIf I had a os to selection with the CSS linguistic communication authors when it comes to transitions, it's that ease
is poorly named. It isn't descriptive at all; literally all timing functions are eases of ane sort or some other!
That nitpick aside, ease
is awesome. Unlike ease-in-out
, information technology isn't symmetrical; information technology features a cursory ramp-up, and a lot of deceleration.
ease
is the default value — if you don't specify a timing function, ease
gets used. Honestly, this feels right to me. ease
is a great pick in most cases. If an element moves, and isn't entering or exiting the viewport, ease
is usually a good choice.
Link to this heading
Custom curvesIf the provided built-in options don't suit your needs, you can define your own custom easing curve, using the cubic bézier timing function!
All of the values we've seen so far are really just presets for this cubic-bezier
function. It takes iv numbers, representing 2 control points.
Bézier curves are really nifty, but they're beyond the scope of this tutorial. I'll be writing more about them soon though!
In the meantime, you lot can start creating your own Bézier timing functions using this wonderful helper from Lea Verou:
Once you come with an animation curve you're satisfied with, click "Re-create" at the peak and paste it into your CSS!
You can besides option from this extended set of timing functions. Though beware: a few of the more outlandish options won't work in CSS.
When starting out with custom Bézier curves, it can be hard to come upwardly with a curve that feels natural. With some do, however, this is an incredibly expressive tool.
Link to this heading
Animation performanceEarlier, we mentioned that animations ought to run at 60fps. When we do the math, though, we realize that this means the browser only has 16.6 milliseconds to paint each frame. That'due south really not much time at all; for reference, information technology takes us almost 100ms-300ms to blink!
If our animation is likewise computationally expensive, it'll announced janky and stuttery. Frames will get dropped, as the device tin can't proceed upward.
Experience this for yourself by tweaking the new "Frames per second" control:
In exercise, poor performance will ofttimes take the grade of variable framerates, so this isn't a perfect simulation.
Animation operation is a surprisingly deep and interesting surface area, well beyond the scope of this introductory tutorial. Just permit's encompass the absolutely-critical, need-to-know bits:
-
Some CSS backdrop are wayyy more expensive to animate than others. For example,
superlative
is a very expensive property because it affects layout. When an element'southward elevation shrinks, it causes a concatenation reaction; all of its siblings will likewise need to move up, to fill the infinite! -
Other backdrop, like
background-color
, are somewhat expensive to breathing. They don't affect layout, but they do require a fresh coat of paint on every frame, which isn't cheap. -
Ii properties —
transform
andopacity
— are very cheap to animate. If an blitheness currently tweaks a property likewidth
orleft
, it can exist greatly improved by moving it totransform
(though it isn't always possible to achieve the exact same effect). -
Be sure to test your animations on the lowest-terminate device that your site/app targets. Your evolution car is likely many times faster than it.
If you're interested in learning more than about animation performance, I gave a talk on this subject at React Rally. Information technology goes deep into this topic:
Link to this heading
Hardware AccelerationDepending on your browser and OS, you may have noticed a curious little imperfection in some of the earlier examples:
Pay close attention to the messages. Notice how they appear to glitch slightly at the showtime and finish of the transition, equally if everything was locking into place?
This happens considering of a manus-off between the calculator's CPU and GPU. Let me explain.
When we animate an element using transform
and opacity
, the browser volition sometimes effort to optimize this animation. Instead of rasterizing the pixels on every frame, it transfers everything to the GPU equally a texture. GPUs are very good at doing these kinds of texture-based transformations, and as a result, nosotros become a very slick, very performant animation. This is known as "hardware acceleration".
Here's the trouble: GPUs and CPUs return things slightly differently. When the CPU hands it to the GPU, and vice versa, you become a snap of things shifting slightly.
We can prepare this problem past adding the post-obit CSS property:
will-change
is a holding that allows u.s. to hint to the browser that we're going to animate the selected element, and that information technology should optimize for this case.
In practice, what this means is that the browser will let the GPU handle this element all the fourth dimension. No more handing-off betwixt CPU and GPU, no more than telltale "snapping into place".
will-change
lets us be intentional about which elements should be hardware-accelerated. Browsers accept their own inscrutable logic around this stuff, and I'd rather not get out information technology upward to chance.
There'south some other benefit to hardware acceleration: we can take advantage of sub-pixel rendering.
Check out these two boxes. They shift downwards when you hover/focus them. One of them is hardware-accelerated, and the other i isn't.
Code Playground
It's maybe a bit subtle, depending on your device and your display, merely one box moves much more than smoothly than the other.
Properties like margin-top
can't sub-pixel-return, which means they demand to round to the nearest pixel, creating a stepped, janky event. transform
, meanwhile, can smoothly shift between pixels, thanks to the GPU'south anti-aliasing trickery.
Link to this heading
UX touchesLink to this heading
Action-driven motionAllow's take another look at our rising "Hello World" button.
As it stands, nosotros have a "symmetrical" transition — the enter animation is the aforementioned as the leave animation:
-
When the mouse hovers over the chemical element, it shifts up by 10 pixels over 250ms
-
When the mouse moves abroad, the element shifts down by 10 pixels over 250ms
A beautiful little item is to give each action its own transition settings. For hover animations, I similar to make the enter animation quick and snappy, while the leave animation can be a scrap more relaxed and lethargic:
Lawmaking Playground
Another common example is modals. It can exist useful for modals to enter with an ease-out
animation, and to exit with a quicker ease-in
animation:
This is a small detail, but it speaks to a much larger idea.
I believe nearly developers call up in terms of states: for example, you might look at this state of affairs and say that we have a "hover" country and a default state. Instead, what if nosotros thought in terms of actions? We animate based on what the user is doing, thinking in terms of events, not states. We have a mouse-enter animation and a mouse-leave animation.
Tobias Ahlin shows how this idea can create next-level semantically-meaningful animations in his blog mail, Meaningfun Motility with Action-Driven Animation.
Link to this heading
DelaysWell, nosotros've come pretty far in our quest to become proficient with CSS transitions, just at that place are a couple final details to get over. Allow's talk about transition delays.
I believe that just about everyone has had this frustrating experience before:
Image courtesy of Ben Kamens
Every bit a developer, y'all can probably work out why this happens: the dropdown just stays open while being hovered! As we motion the mouse diagonally to select a kid, our cursor dips out-of-bounds, and the carte du jour closes.
This trouble tin be solved in a rather elegant way without needing to reach for JS. We can use transition-delay
!
transition-filibuster
allows us to go on things status-quo for a brief interval. In this case, when the user moves their mouse exterior .dropdown-wrapper
, nothing happens for 300ms. If their mouse re-enters the element inside that 300ms window, the transition never takes place.
Later 300ms elapses, the transition
kicks in normally, and the dropdown fades out over 400ms.
Link to this heading
Doom flickerWhen an element is moved upward or down on hover, nosotros need to be very careful we don't accidentally introduce a "doom flicker":
Alarm: This GIF includes flickering motion that may potentially trigger seizures for people with photosensitive epilepsy.
You may have noticed a similar result on some of the demos on this folio!
The trouble occurs when the mouse is near the element'southward boundary. The hover effect takes the chemical element out from under the mouse, which causes it to autumn back downwards under the mouse, which causes the hover issue to trigger again… many times a second.
How do nosotros solve for this? The play tricks is to separate the trigger from the effect. Here'southward a quick example:
Lawmaking Playground
Our <button>
now has a new child, .background
. This span houses all of the corrective styles (background color, font stuff, etc).
When we mouse over the plain-jane button, it causes the child to peek out in a higher place. The push button, withal, is stationary.
Try uncommenting the outline
to see exactly what's going on!
Link to this heading
Respecting motion preferencesWhen I run across a well-crafted animation on the spider web, I react with delight and glee. People are different, though, and some folks have a very unlike reaction: nausea and malaise.
I've written before well-nigh respecting "prefers-reduced-motion", an OS-level setting users can toggle to limited a preference for less motion. Permit'southward apply those lessons here, by disabling animations for folks who request it:
This modest tweak means that animations will resolve immediately for users who have gone into their system preferences and toggled a checkbox.
As front-finish developers, we have a certain responsibility to ensure that our products aren't causing damage. This is a quick footstep nosotros tin perform to make our sites/apps friendlier and safer.
Link to this heading
The bigger moving pictureCSS transitions are fundamental, only that doesn't mean they're easy. There's a surprising amount of depth to them; even in this long-winded blog postal service, I've had to cut some stuff out to go on information technology manageable!
Web animations are more of import than near developers realize. A unmarried transition hither or there won't make or break an experience, only it adds up. In aggregate, well-executed animations can have a surprisingly profound effect on the overall user experience.
Transitions can make an app experience "real". They tin can offer feedback, and communicate in a more-visceral style than re-create lonely. They can teach people how to use your products. They can spark joy.
If you lot enjoyed this tutorial, yous might exist pleased to know that I've built a CSS course. In fact, this blog postal service is derived from i of the lessons in the Animations module!
It's congenital on the same tech stack as this blog, so it features the same manner of embedded interactive widgets, but it goes even farther. My course features videos, minigames, workshops, and so much more than.
You lot tin learn more at its official website, CSS for JavaScript Developers.
Finally, no interactive lesson is complete without a "sandbox manner"! Play with all the previous settings (and a couple new ones!) and create some generative art with this open-ended widget:
Source: https://www.joshwcomeau.com/animation/css-transitions/
0 Response to "The Art of Transition Unique Transition Sweep Fx"
Post a Comment