CSS @keyframes is used to define the various stages and changes of animations. 1) Basic use: define animations through @keyframes, such as fadeIn changing from transparent to opaque. 2) Loop animation: Use the infinite keyword to create continuous rotation effects. 3) Performance optimization: Use the will-change attribute to improve animation fluency. 4) Accessibility: Adjust animations to suit user preferences through prefers-reduced-motion media query. 5) Flexible control: combine CSS variables to achieve color change animation. 6) Adjust the effect: Make the animation more natural by modifying the duration and timing-function.
The CSS @keyframes
rule is the core of animation, which defines the various stages and changes of animation. In this article, we will dive into how to use @keyframes
to create rich animation effects, not just simple transitions, but also some complex application scenarios and best practices.
When it comes to the application of @keyframes
, we need to consider its importance in modern web design. Animation is not only a visual decoration, but also an important means to enhance user experience. With @keyframes
we can precisely control the changes of elements on the timeline, resulting in smooth and compelling animation effects.
Let's start with a simple example to illustrate the basic usage of @keyframes
:
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .fade-in { animation: fadeIn 2s ease-in; }
In this example, we define an animation called fadeIn
, which gradually changes from completely transparent ( opacity: 0
) to completely opacity ( opacity: 1
). We then apply this animation to an element with a class fade-in
, set the animation duration to 2 seconds, and use ease-in
as the transition effect.
Now, let's explore more in-depth @keyframes
' usage tips and some advanced applications.
First, we can use @keyframes
to create loop animations, which is very useful when creating load indicators or background animations:
@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } .loading-spinner { animation: spin 1s linear infinite; }
In this example, the spin
animation causes the elements to rotate continuously, and the infinite
keyword ensures that the animation loops infinitely. linear
ensures constant rotation speed and does not have the effect of acceleration and deceleration like ease-in
.
When using @keyframes
, we also need to pay attention to the performance of animations. Too much complex animation can lead to page performance degradation, especially on mobile devices. To optimize performance, we can use will-change
attribute to prompt the browser which properties will change, so as to prepare in advance:
@keyframes slideIn { from { transform: translateX(-100%); } to { transform: translateX(0); } } .slide-in { will-change: transform; animation: slideIn 0.5s ease-out; }
Here, we use will-change: transform
to tell the browser that transform
attribute will change, which helps improve the smoothness of the animation.
Another aspect to consider is the accessibility of animations. Animation can cause discomfort among some users, especially those with epilepsy or dysmotic disorders. To do this, we can use prefers-reduced-motion
media query to detect user preferences and adjust the animation accordingly:
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .fade-in { animation: fadeIn 2s ease-in; } @media (prefers-reduced-motion: reduce) { .fade-in { animation: none; } }
With this setting, our animations will be disabled when the user enables the Reduce Motion option, thus improving the accessibility of the web page.
In actual projects, I found that @keyframes
can be used in conjunction with CSS variables (Custom Properties) to achieve more flexible animation control. For example, we can define an animation of color changes and use CSS variables to control the color:
:root { --start-color: #ff0000; --end-color: #00ff00; } @keyframes colorChange { from { background-color: var(--start-color); } to { background-color: var(--end-color); } } .color-change { animation: colorChange 3s ease-in-out infinite alter; }
In this example, we use CSS variables to define the start and end colors of the animation, so that the animation effect can be easily adjusted without modifying the @keyframes
rule.
Finally, I want to share a problem I have encountered: When using @keyframes
, if the animation lasts too short, it may cause the animation to look not smooth enough. To solve this problem, I usually adjust the duration of the animation and try different timing-function
to find the best results:
@keyframes bounce { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-20px); } } .bounce { animation: bounce 0.8s ease-in-out infinite; }
In this example, I found that setting the animation time to 0.8 seconds and using ease-in-out
as the timing function makes the bounce effect more natural and smooth.
In general, @keyframes
is a powerful and flexible tool in CSS, through which we can create a variety of complex and compelling animation effects. Through the introduction and examples of this article, I hope you can better understand how @keyframes
is used and flexibly apply these techniques in real projects.
The above is the detailed content of @keyframes CSS: Best code examples. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

exit() is a function in PHP that is used to terminate script execution immediately. Common uses include: 1. Terminate the script in advance when an exception is detected, such as the file does not exist or verification fails; 2. Output intermediate results during debugging and stop execution; 3. Call exit() after redirecting in conjunction with header() to prevent subsequent code execution; In addition, exit() can accept string parameters as output content or integers as status code, and its alias is die().

The rational use of semantic tags in HTML can improve page structure clarity, accessibility and SEO effects. 1. Used for independent content blocks, such as blog posts or comments, it must be self-contained; 2. Used for classification related content, usually including titles, and is suitable for different modules of the page; 3. Used for auxiliary information related to the main content but not core, such as sidebar recommendations or author profiles. In actual development, labels should be combined and other, avoid excessive nesting, keep the structure simple, and verify the rationality of the structure through developer tools.

There are three main differences between Callable and Runnable in Java. First, the callable method can return the result, suitable for tasks that need to return values, such as Callable; while the run() method of Runnable has no return value, suitable for tasks that do not need to return, such as logging. Second, Callable allows to throw checked exceptions to facilitate error transmission; while Runnable must handle exceptions internally. Third, Runnable can be directly passed to Thread or ExecutorService, while Callable can only be submitted to ExecutorService and returns the Future object to

The key to Java exception handling is to distinguish between checked and unchecked exceptions and use try-catch, finally and logging reasonably. 1. Checked exceptions such as IOException need to be forced to handle, which is suitable for expected external problems; 2. Unchecked exceptions such as NullPointerException are usually caused by program logic errors and are runtime errors; 3. When catching exceptions, they should be specific and clear to avoid general capture of Exception; 4. It is recommended to use try-with-resources to automatically close resources to reduce manual cleaning of code; 5. In exception handling, detailed information should be recorded in combination with log frameworks to facilitate later

Java's class loading mechanism is implemented through ClassLoader, and its core workflow is divided into three stages: loading, linking and initialization. During the loading phase, ClassLoader dynamically reads the bytecode of the class and creates Class objects; links include verifying the correctness of the class, allocating memory to static variables, and parsing symbol references; initialization performs static code blocks and static variable assignments. Class loading adopts the parent delegation model, and prioritizes the parent class loader to find classes, and try Bootstrap, Extension, and ApplicationClassLoader in turn to ensure that the core class library is safe and avoids duplicate loading. Developers can customize ClassLoader, such as URLClassL

InPHP,variablesarepassedbyvaluebydefault,meaningfunctionsorassignmentsreceiveacopyofthedata,whilepassingbyreferenceallowsmodificationstoaffecttheoriginalvariable.1.Whenpassingbyvalue,changestothecopydonotimpacttheoriginal,asshownwhenassigning$b=$aorp

Javaprovidesmultiplesynchronizationtoolsforthreadsafety.1.synchronizedblocksensuremutualexclusionbylockingmethodsorspecificcodesections.2.ReentrantLockoffersadvancedcontrol,includingtryLockandfairnesspolicies.3.Conditionvariablesallowthreadstowaitfor

When you encounter the prompt "This operation requires escalation of permissions", it means that you need administrator permissions to continue. Solutions include: 1. Right-click the "Run as Administrator" program or set the shortcut to always run as an administrator; 2. Check whether the current account is an administrator account, if not, switch or request administrator assistance; 3. Use administrator permissions to open a command prompt or PowerShell to execute relevant commands; 4. Bypass the restrictions by obtaining file ownership or modifying the registry when necessary, but such operations need to be cautious and fully understand the risks. Confirm permission identity and try the above methods usually solve the problem.
