Create cool UI animations with CSS

Animation is an important part of modern UX and is easier than ever to implement with CSS. While it may seem limited or a lesser tool when it comes to animation, CSS is actually a really powerful tool and is capable of producing beautifully smooth 60fps animations. In this feature we'll explore everything from reasoning and planning to implementation.

Read on to learn about CSS transitions, or jump to page 2 for CSS keyframes, page 3 for a closer look at animation performance, page 4 for a guide to animating SVG. Or click through to page 5 to see how to bring it all together to create a UI animation.

Need some more inspiration? Take a look at our roundup of awesome CSS animation examples (and how to code them).

CSS transitions

Put simply, CSS transitions are a way to provide animation between two property values. For the animation to trigger, something needs to change in the application or website. CSS transitions can be used to achieve a number of animated effects, from a simple colour change to more complex transitions.

Transitions in CSS are simple, we just need to choose what elements to transition and when. For example, if we have a button and we want to change the background colour gradually instead of instantly when the user hovers over the button, we use a transition.

Transition syntax

Transitions in CSS are made up of four properties. These give us control over how the transition will animate.

transition-property
This enables us to choose which properties we want to animate. We can transition a number of different properties. See a full list of transition-property properties.

transition-duration
This property enables us to control how long the transition from one property value to another will take. This can be defined in either seconds (s) or milliseconds (ms).

transition-timing-function
Timing functions, or 'easing', enable us to adjust the rate of change over time. There are a number of keywords we can use. For example, the linear keyword will transition from A to B at an equal tempo, whereas ease-in-out will start slowly, speed up in the middle and slow down towards the end. Custom timing functions can also be defined using the cubic-bezier property. See a full list of timing keywords.

transition-delay
Transitions can be delayed using this property and is set using seconds or milliseconds.

Transition shorthand

All of the transition properties listed above can be combined into a shorthand statement using the transition property.

We are free to omit the values we don't need in order to set the defaults.

Combining transitions

You can combine multiple transitions to create choreographed animations. Check this example:

Browser support

Support for transitions and animations in modern browsers is really good. Everything from Internet Explorer 11 or above is going to support the majority of the code needed for animation.

There are exceptions with some of the newer animation properties; CSS Motion Path, for example, or when using SVG or custom properties (CSS variables) as part of the animation.

Prefixing for the most part is probably not needed unless we need to provide support for Internet Explorer 10 and below. There are several ways we can prefix code if needed. Auto-prefixer is a really useful tool that can be used as part of a build process or manually at the end of a project. It enables us to configure the browser support you need, then it will automatically prefix our code where needed. 

We can also check the support for any property using the amazing tool CanIUse. Simply type in the property we want to use and see which browsers  are supported.

Next page: A guide to CSS keyframes

CSS keyframes are used for complex or repeatable animations. They enable us to define multiple property values to animate between. Keyframe animations can be reused and repeated, unlike CSS transitions.

CSS keyframe animations are defined using the @keyframes syntax. This works much like a media query where we nest elements inside of the @ statement. Inside the keyframe declaration we have two options: we can use the keyword to and from or we can define our timeline using percentages. 

Keyword animations

When the animation we're creating only has two points to animate between, we can use the to and from syntax, in fact we can use just to, providing the original property value is set on the element we're going to be animating.

Percentage animations

When creating animations where we need to define more than one point to animate, we can use percentages. This enables us to have precise control over our animation.

Applying an animation

Animation in CSS has a number of properties we can set in order to have precise control over the playback of our keyframe animations. Some, like animation-duration, animation-delay, animation-iteration-count, animation-play-state and animation-name are all fairly self-explanatory, while some of the other properties can be a little trickier to learn and utilise to their full potential.

animation-timing-function
Timing functions in animation are the same as transitions – we can use either keywords or set a custom timing function by using the cubic-bezier value. Take a look at a full list of timing keywords.

animation-direction
When applying our animations, we have the ability to play them back in a number of ways. The default value is normal, which will play the animation forwards. We can also play the animation in reverse or alternate the animations playing forwards and backwards.

animation-fill-mode
The fill mode value enables us to choose what should happen at the end of an animation to the value that we have changed. For example, setting the value to forwards will keep the property values from the end of the animation, whereas the default value none will return the elements to their original state after the animation has finished.

Animation shorthand

All of the animation properties can be combined into a shorthand statement using the 'animation' property. We are free to omit the values we do not need and want to leave as the default values.

Next page: Learn how to manage the performance of your animations

Page speed and performance is an important aspect of any application or website. If you are using animation as part of your project, it can be a good place to start when trying to optimise performance. Animating too much or too many properties will cause animations to stutter.

Firstly you can check that you're not using too many animations all at once on the page: as well as being bad for performance, it is also bad for your users' experience. Multiple animations on different parts of the page will be fighting for their attention as well as potentially causing performance issues. Being aware of the number of animations will help to address both of these potential issues. 

What causes janky animations?

In order to achieve a smooth 60fps animation, the browser has only 16.7ms (1000ms/60) to achieve all of the work that needs to be done per frame. If the browser can't complete all of the operations needed, it will stop and move on to the next frame, starting the calculation and redrawing process all over again. This is when we start to see dropped frames, causing janky or stuttering animations.

How to avoid janky animations

While the list of animatable properties is extensive, at the moment we can only safely animate a handful of these properties to keep within the necessary 16.7ms. These properties are transform, opacity and filter.

The reason for this is that animating any other property will cause the browser to have to repaint the page, and this is an expensive process in terms of performance and will likely take longer than 16.7ms to calculate and draw each change.

We can also give the browser a helping hand by utilising the will-change property, which gives it a heads up that a property is going to change. This enables the browser to perform some optimisations before your animation even starts.

The future of web animation performance

The new Firefox Quantum project is taking amazing strides towards making every animatable property perform well, as well as many other improvements to rendering content on the web.

It's also worth noting that the newest versions of the iPad will play animations back at 120fps, which will reduce the time in which the browser has to calculate and paint each frame to 8.35ms.

Timing and choreography

Utilising the correct timing and delays will produce animations that look better and are easier to comprehend. When animating any elements, it's important to choose a duration that is appropriate to its context. For example, an animation that's applied to a button interaction should be short, usually less than a second. 

Utilising long animations for common interactions is tedious and annoying to the user and can make your application or website feel sluggish and slow. However, providing an animation duration that is too short can cause confusion and provoke the wrong emotions and feelings for your audience. Once you have chosen a comfortable animation duration, you should use this in every aspect of your website or application.

When animating, multiple elements or property delays should be used to enhance comprehension. It's much easier to see what's happening in an animation when one thing happens at a time instead of all at once. 

Next page: Learn how to animate SVG

SVG has many benefits – its vector nature is great, and we don't get any of the problems we get with bitmap images when displaying an image too big or too small or on devices with differing DPIs. SVG is also much smaller in size. SVGs are basically instructions for the browser to draw the image contained within.

How do I animate SVG?

SVG enables us to create intricate drawings and images, where all of the elements inside SVG can be animated using CSS.

Animation in SVG works exactly the same way as it does with any element on the page. We need some way to target the element we want to animate, and then apply the animation.

The main way in which animating SVG elements differs from regular elements is the transform-origin property. Normally we would use percentages or keyword values in order to set the point at which a transform operation takes place.

So if we can't use keywords and can't use percentages, how do we set our transform origin? The answer is to use pixel values. Further complications come into play because, unlike regular elements that would measure the pixels from the top left corner of itself, SVGs will measure from the top left corner of the parent SVG canvas. This blog post covers the topic in detail.

Finally, a note on browser support: CSS animation when used with SVG requires the SVG to be inline in the page for the majority of browsers. This means we can't use the image tag to include our SVG and perform animations; we need to have our SVG inside an SVG tag on the page.

desktop windows illustration

Custom properties

Custom properties, or CSS variables, can be used to create configurable parts of your animation. Animations and movement can cause motion sickness in some users. We can use custom properties in order to effectively remove animations for users who have indicated preferring reduced motion.

By changing the timing to 0, we stop the animation from running when the user has requested it. While this media query isn't yet widely supported, it is by iOS.

We can use custom properties to define other parts of our animation, such as the colour or size and use. This is useful if we have a part that's configurable and we're using that property as part of an animation.

Next page: Bring everything together in a UI animation

In this final tutorial we'll look at how we can combine all of the elements we've covered in the article into one single animation. 

We'll be creating a record player animation where the arm of the record player moves into position over the record, as well as rotating the record itself at two different speeds. We'll create the animation using SVG transitions and keyframes, and we'll be using custom properties in order to make our animation configurable.

01. Create and export our SVG

The first step is to create and export our SVG code. You can do this using many different graphics editors (the example is Sketch for Mac). The shapes being used are simple – mostly straight and poly lines combined with circles. We want to create the SVG in the initial state of our animation.

02. Optimise our SVG

When we have the exported code from our editor we need to optimise that code to make it easier for us when creating our animation. Firstly we'll run it through SVGOMG making sure to only optimise the parts we need. Once we've done this, we'll paste our code into CodePen and create some basic page styles. We'll be using Sass to take advantage of the nesting capability.

03. Edit by hand

Next we will need to edit our SVG by hand. We are going to need to remove any inline transforms on elements that we are going  to animate into our CSS. Doing this will make it easier to animate, because we'll be able to see all of our transform properties in one place.

04. Animate the arm

We can achieve most of what we are trying to do using transitions. We will start with the record arm and animating the arm into position over the record. To do this we will need to rotate the arm of the record from -90deg to 0deg. In order to transition rotation we need to use the transform property. This means we also need to keep any other transform properties the same when changing the rotation.

05. Slowly rotate the record

Next we can use another transition to complete the first, slower rotation of our record. To do this we will need to target the container and apply our transition code, much like we did in the previous step, except this time we will be adding a delay of a quarter of the time it takes for the arm to move into position.

06. Speed up the rotation

In order to speed up the rotation, and for it to repeat infinitely, we'll need to use a keyframe animation. The animation we need to create is simple, we just need to rotate the record 360 degrees.

Then when we're applying our animation, we need to make sure to set the delay correctly so our animation starts at the end of the container stopping.

07. Reverse the movement

Everything is working now and our animation is complete – until the interaction stops. At that point, both the arm and record stop animating and jump back to their original positions. This is where the setup of our SVG is important. The record element itself sits inside of a container. By animating the container using a transition we can also perform another transition in reverse with just a couple of lines of code.

08. Introduce custom properties

Now we've got our complete animation, we'll make it configurable with custom properties. We can do this by setting our custom properties on the root element in our CSS.

We can then apply them to the property values where needed, making sure to provide a fallback for each one.

We can also use custom properties as part of calc() functions, which is particularly useful for sizing and for creating durations and delays.

09. Make the duration configurable

We can utilise the calc() function in order to make the animation duration configurable. Firstly we need to set a new custom property for our duration with a value, in seconds. We can then use this value in order to set all of the other animation time values.

Given the custom property --animation-duration being two seconds becomes:

By doing this for every time value in our animation, we can control the speed of the entire animation by simply changing the custom property at the top of our CSS.

10. Optimise the animation

Now we can add our accessibility options for prefers-reduced-motion and add the will-change property to all of the elements.

This article was originally published in creative web design magazine Web Designer. Buy issue 282 or subscribe.

Read more: 



Contributer : Creative Bloq
Create cool UI animations with CSS Create cool UI animations with CSS Reviewed by mimisabreena on Wednesday, February 13, 2019 Rating: 5

No comments:

Sponsor

Powered by Blogger.