An assortment of ready-to-use cross-browser animations known as Animate.css can be utilized in your web applications. It is ideal for drawing attention, creating sliders, enhancing homepages, and emphasizing certain elements.
Installation and Usage
Using npm for installation:
$ npm install animate.css --save
Alternatively, you can opt for installation via Yarn (this necessitates appropriate tools like Webpack, Parcel, etc.). In case you are not utilizing any bundling or packaging tools for your code, you can employ the CDN method outlined below:
$ yarn add animate.css
Import it into your file:
import 'animate.css';
Or add it directly to your webpage using a CDN:
<head>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"
/>
</head>
A negative animation-delay value provides an alternative approach. Similar to "0s," a negative number signifies that the animation will commence immediately upon implementation. Additionally, it will progress automatically based on the absolute value of the delay.
This creates the perception that the animation is already in progress due to its initiation at the specified time in the past. By setting the animation-delay property to a negative value like "-2s," the animation will commence immediately upon application, giving the illusion that it commenced two seconds prior.
Basic Usage
Once Animate.css has been successfully installed, you can assign any animation name to an element and include the class animateanimated (remember to include the animate prefix!).
<h1 class="animate__animated animate__bounce">An animated element</h1>
And that concludes the process! A CSS animation component is now available. Wonderful!
// While animations can improve the overall user experience of an interface, it is important to note that they can also hinder users' navigation. To guarantee the seamless execution of your web projects, we recommend reviewing the segments on optimal strategies and common pitfalls.
Using @keyframes
You have the option to directly utilize the animation keyframes provided by the library, despite the availability of a few handy classes like the animated class, which are designed to help you kickstart the process swiftly. This approach provides a flexible way to integrate Animate.css into your current projects without the need to make alterations to your HTML markup.
Example:
.my-element {
display: inline-block;
margin: 0 0.5rem;
animation: bounce; /* referring directly to the animation's @keyframe declaration */ animation-duration: 2s; /* do not forget to set a duration! */
}
NOTE: The animation-timing attribute specified on the animation's class affects some animations. Modifying it or not revealing it might have unanticipated consequences.
CSS Custom Properties (CSS Variables)
Since version 4, the duration, timing, and repetition of the animation are specified through custom properties known as CSS variables in Animate.css. As a result, Animate.css is highly flexible and can be easily tailored to suit different needs. If you wish to adjust the length of the animation, you have the option to modify the value either on a specific element or apply it universally across your project.
Example:
/* This only changes this particular animation duration */ .animate__animated.animate__bounce {
--animate-duration: 2s;
}
/* This changes all the animations globally */
:root {
--animate-duration: 800ms;
--animate-delay: 0.9s;
}
Furthermore, custom variables facilitate quick adjustments to all time-sensitive properties within your animation. This means that a single line of JavaScript code could result in a slow-motion or time-lapse impact:
// It will take twice as long to complete every animation document.documentElement.style.setProperty('2s', '--animate-duration');
// It will take half as long to complete all animations document.documentElement.style.set'--animate-duration', '.5s', property;
Animate.css provides a reliable alternative, broadening its compatibility to include all browsers that are capable of rendering CSS animations, even if some older browsers lack support for specific features.
Utility Classes
Several convenient utility classes are provided in CSS to simplify usage.
Delay Classes
Delays can be inserted directly into a class property of an element as outlined in the following way:
<div class="animate__animated animate__bounce animate__delay-2s">Example</div>
Animate.css provides the following delays:
Class Name & The default delay time includes animatedelay-2s~2s, animatedelay-3s~3s, animatedelay-4s~4s, and animatedelay-5s~5s.
There are delays varying from one to five seconds. Customizing the duration of the --animate-delay attribute allows you to tailor them:
** The start time of all delay classes will be doubled.
:root {
--animate-delay: 2s;
}
/* The start time of all delay classes will be halved */
:root {
--animate-delay: 0.5s;
}
Slow, Slower, Fast, and Faster Classes
By incorporating the specified classes, you can modify the speed of the animation:
<div class="animate__animated animate__bounce animate__faster">Example</div>
Class name & Default speed time for animation are as follows:
- animate__slow takes 2 seconds
- animate__slower takes 3 seconds
- animate__fast takes 800 milliseconds
- animate__faster takes 500 milliseconds
The default duration for the animate__animated class is 1 second. By using the --animate-length parameter, you can adjust the length of the animation either on a specific element or across the entire project. This adjustment will affect all utility classes and animations uniformly. As an example:
/* All animations will take twice as long to finish */
:root {
--animate-duration: 2s;
}
*/ My element {
--animate-duration: 0.5s;
}
You may notice that certain animations have a brief duration. These proportions will be maintained when specifying the duration using the --animation-duration attribute, similar to how we utilized the CSS calc function. Consequently, all animations will adjust accordingly to any modifications in the overall duration!
Repeating Classes
By incorporating these classes, you can modify the number of times the animation repeats.
<div class="animate__animated animate__bounce animate__repeat-2">Example</div>
Class Name & Default iteration count animaterepeat-1 1 animaterepeat-2 2 animaterepeat-3 3 animateinfinite infinite
The animate__repeat class, similar to the delay and speed classes, defaults to a single iteration and relies on the --animate-repeat parameter. Modifying the --animate-repeat parameter allows for customization of these settings:
// The component will play the animation two times consecutively.
// It's recommended to configure this attribute on a local level instead of globally to prevent potential complexities */
.my-element {
--animate-repeat: 2;
}
Animate__infinite does not make use of any custom variables, so adjustments to --animate-repeat will not affect the outcome. To optimize repetitive animations, be sure to review the recommendations in the best practices portion.
Best Practices
Engaging animations can greatly improve the user experience of an interface, but it is essential to follow specific principles to maintain a balance and prevent your digital products from becoming overwhelming for users. The recommendations provided below are designed to help you get off to a good start.
- Significant animations
An element should not be animated solely for decorative purposes. It is important to ensure that animations effectively convey a specific message. Attention-grabbing animations like bounce, flash, pulse, and similar effects should be employed to emphasize a specific aspect of your interface, rather than simply for visual appeal.
Utilizing animations for entry and exit transitions is essential to assist users in navigating the interface and recognizing transitions into different states.
It's not suggesting you avoid injecting some humor into the UI; instead, ensure that the animations do not hinder the user's experience or have a detrimental effect on the page's performance when overused.
- Avoid animating sizable elements
Avoid using animations that may cause confusion to users without providing any value. Moreover, there is a high probability that poorly executed animations can result in a negative user experience.
- Avoid animating root elements.
Although it is possible, it is advisable to avoid animating the <code>or</code> tags. There have been documented instances suggesting that such actions could potentially lead to unexpected browser malfunctions. Furthermore, continuously bouncing the entire page is unlikely to enhance the user experience significantly. If you truly desire this type of animation, consider employing an <code>element</code> and applying the animation selectively on your website, as demonstrated in the following illustration:
- It is recommended to steer clear of infinite animations.
Avoid incorporating endless animations, even though Animate.css provides utility classes for repetitive animations, including an infinite option. This can lead to user distraction and potential irritation. Therefore, exercise caution when considering its utilization!
- Be mindful of the starting and ending states of your elements.
The animation-fill-mode CSS attribute controls how an element appears before and after an animation. It is a standard feature in all Animate.css animations. Feel free to customize animation-fill-mode: both within Animate.css as necessary, although this is the default behavior.
- Avoid disabling the prefers-reduced-motion media query.
Animate.css has included support for the prefers-reduced-motion media query starting from version 3.7.0. This media query allows animations to be disabled according to the user's operating system preference on supported browsers (which include many up-to-date browsers). This crucial accessibility feature should always remain enabled to support users dealing with vestibular and seizure issues. It is a native browser feature designed to assist these users. Explore more details about it by visiting this link. Remember to inform users if your web application relies on animations to function properly, without actually disabling the animation functionality. Achieving this with just CSS is a straightforward process. Below is a straightforward example:
Gotchas
- Animating inline elements is not possible.
Although inline elements may animate in certain browsers, this action goes against the CSS animation standards, causing issues in specific browsers and eventually leading to the animation ceasing to function. It is recommended to animate block or inline-block-level elements instead (such as children, flex containers, and grids, which are also block-level elements). When animating an inline-level element, one solution is to adjust the display property to inline-block.
- Overflow
Animate.css animations typically involve shifting elements along the screen and sometimes trigger scrollbars on your webpage. You can manage this behavior by using the overflow: hidden CSS property. The main idea is to apply this property to the parent element that contains the animated item, though there are no strict guidelines on where or when to use it. It's up to you to decide the appropriate timing and placement for its usage, and this tutorial is designed to support you in making that decision.
- Time Gaps for Repetitions
Unfortunately, this cannot be achieved solely with CSS at the moment. The solution requires the utilization of JavaScript.
- Implementing with JavaScript
When integrated with JavaScript, animate.css can be employed for a variety of extra functionalities. For instance:
element.classList.add('animate__animated', 'animate__bounceOutLeft'); const element = document.querySelector('.my-element');
When an animation finishes, it can be detected:
element.classList.add('animate__animated', 'animate__bounceOutLeft'); const element = document.querySelector('.my-element');
element.addEventListener('animationend', () => { // do something }); or change its duration:
or change its duration:
element.style.setProperty('--animate-duration', '0.5s'); const element = document.querySelector('.my-element');
To automatically include or remove the animation classes, you have the option to utilize the subsequent simple function:
const animateCSS = (element, animation, prefix = 'animate__') =>
// We create a Promise and return it
new Promise((resolve, reject) => {
const animationName = `${prefix}${animation}`;
const node = document.querySelector(element);
node.classList.add(`${prefix}animated`, animationName);
// When the animation ends, we clean the classes and resolve the Promise
function handleAnimationEnd(event) {
event.stopPropagation();
node.classList.remove(`${prefix}animated`, animationName);
resolve('Animation ended');
}
node.addEventListener('animationend', handleAnimationEnd, {once: true});
});
And use it like this:
animateCSS('.my-element', 'bounce');
// or
animateCSS('.my-element', 'bounce').then((message) => {
// Do something after the animation
});
If the previous function is difficult to understand, you may find it beneficial to explore const, classList, arrow functions, and promises for assistance.
Migration from v3.x and Under
Upgrading is beneficial as moving from version 3.x to UnderAnimate.css version 4 introduces various improvements, such as updated and improved animations. One notable change is the addition of a prefix (animate__ by default) to all Animate.css classes, which complicates a straightforward migration process.
We provide the animate.compat.css file, which does not include any prefixes, similar to the previous versions (3.x and older), despite the fact that the default build, animate.min.css, includes the animate__ prefix.
Update your import if you are using a bundler:
From:
'animate.min.css' is imported;
'animate.compat.css' is imported;
Please be aware that this could differ slightly depending on the configuration of your project.
When incorporating a CDN, ensure to revise your HTML hyperlink.
From:
<head>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css"
/>
</head>
To
<head>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.0.0/animate.compat.css"
/>
</head>
It is highly recommended to utilize the prefixed default version for new projects to minimize the likelihood of class conflicts. Additionally, there is a possibility that the animate.compat.css file will be excluded in upcoming updates.
Modifying the Prefix By Default
Altering the prefix of animation on a customized build is a straightforward process. Update the prefix property in the animateConfig.json file within the package, then execute npm start to compile the library.
"animateConfig": {"prefix": "myCustomPrefix__"}, then: /* on Animate.css package.json */
$ npm start
Accessibility
Individuals with motion sensitivity have the option to opt-out of viewing animations through the prefers-reduced-motion media query, a feature that is compatible with Animate.css. Alternatively, users can enable the "reduce motion" setting in their operating system to disable CSS transitions automatically, a functionality supported by all prevalent browsers and operating systems, including mobile devices.