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

ReadonlypropertiesinPHP8.2canonlybeassignedonceintheconstructororatdeclarationandcannotbemodifiedafterward,enforcingimmutabilityatthelanguagelevel.2.Toachievedeepimmutability,wrapmutabletypeslikearraysinArrayObjectorusecustomimmutablecollectionssucha

SetupaMaven/GradleprojectwithJAX-RSdependencieslikeJersey;2.CreateaRESTresourceusingannotationssuchas@Pathand@GET;3.ConfiguretheapplicationviaApplicationsubclassorweb.xml;4.AddJacksonforJSONbindingbyincludingjersey-media-json-jackson;5.DeploytoaJakar

First, use JavaScript to obtain the user system preferences and locally stored theme settings, and initialize the page theme; 1. The HTML structure contains a button to trigger topic switching; 2. CSS uses: root to define bright theme variables, .dark-mode class defines dark theme variables, and applies these variables through var(); 3. JavaScript detects prefers-color-scheme and reads localStorage to determine the initial theme; 4. Switch the dark-mode class on the html element when clicking the button, and saves the current state to localStorage; 5. All color changes are accompanied by 0.3 seconds transition animation to enhance the user

Use datetime.strptime() to convert date strings into datetime object. 1. Basic usage: parse "2023-10-05" as datetime object through "%Y-%m-%d"; 2. Supports multiple formats such as "%m/%d/%Y" to parse American dates, "%d/%m/%Y" to parse British dates, "%b%d,%Y%I:%M%p" to parse time with AM/PM; 3. Use dateutil.parser.parse() to automatically infer unknown formats; 4. Use .d

Yes, a common CSS drop-down menu can be implemented through pure HTML and CSS without JavaScript. 1. Use nested ul and li to build a menu structure; 2. Use the:hover pseudo-class to control the display and hiding of pull-down content; 3. Set position:relative for parent li, and the submenu is positioned using position:absolute; 4. The submenu defaults to display:none, which becomes display:block when hovered; 5. Multi-level pull-down can be achieved through nesting, combined with transition, and add fade-in animations, and adapted to mobile terminals with media queries. The entire solution is simple and does not require JavaScript support, which is suitable for large

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

Full screen layout can be achieved using Flexbox or Grid. The core is to make the minimum height of the page the viewport height (min-height:100vh); 2. Use flex:1 or grid-template-rows:auto1frauto to make the content area occupy the remaining space; 3. Set box-sizing:border-box to ensure that the margin does not exceed the container; 4. Optimize the mobile experience with responsive media query; this solution is compatible with good structure and is suitable for login pages, dashboards and other scenarios, and finally realizes a full screen page layout with vertical centering and full viewport.

Selecting the Java SpringBoot React technology stack can build stable and efficient full-stack web applications, suitable for small and medium-sized to large enterprise-level systems. 2. The backend uses SpringBoot to quickly build RESTfulAPI. The core components include SpringWeb, SpringDataJPA, SpringSecurity, Lombok and Swagger. The front-end separation is achieved through @RestController returning JSON data. 3. The front-end uses React (in conjunction with Vite or CreateReactApp) to develop a responsive interface, uses Axios to call the back-end API, and ReactRouter
