CSS transitions and animations are the core tools for achieving smooth and dynamic web interfaces, both of which work without JavaScript. 1. Use transition to achieve simple interaction: When you only need to smoothly switch between two states (such as hover effect), you should use transition, and priority is given to transitioning transform and opacity attributes to avoid causing re-arranged attributes such as width and height. 2. Use animation to implement complex sequences: When multiple keyframes, loop playback or automatically triggered animations (such as loading animations and entry effects), @keyframes should be used to define animations, which can accurately control the behaviors of iteration-count, direction, fill-mode, etc. 3. Key points of performance optimization: Always give priority to transform and opacity, use transform: translate() instead of top/left positioning, avoid excessive use of will-change, and use box-shadow and filter animations with caution. 4. Accessibility must be supported: close or shorten the animation duration through @media (prefers-reduced-motion: reduce) and respect user preferences. 5. It can be used in combination: for example, modal boxes use animation to enter the field, and close buttons use transition to achieve hover feedback to achieve a distinctive interactive experience. Select the tools correctly and follow best practices to build high-performance, accessible, refined UI animations without JavaScript.
CSS transitions and animations are powerful tools for adding subtle, performant motion to web interfaces. They bring pages to life, improve user experience, and guide attention—without relying on JavaScript. While both create visual changes over time, they serve different purposes and work in distinct ways. Here's a practical guide to using them effectively.

CSS Transitions: Smooth Property Changes
Transitions are best when you want a CSS property to change gradually from one value to another—like fading a button on hover or sliding a menu in.
How They Work
A transition listens for a change in a CSS property (triggered by :hover
, :focus
, JavaScript adding a class, etc.) and smoothly animates that change over a specified duration.

Basic Syntax
.element { background-color: blue; transition: background-color 0.3s ease; } .element:hover { background-color: red; }
Key Properties

-
transition-property
: Which CSS property to animate (eg,opacity
,transform
,color
) -
transition-duration
: How long the animation takes (eg,0.5s
,200ms
) -
transition-timing-function
: Controls the speed curve (eg,ease
,linear
,ease-in-out
) -
transition-delay
: Wait before starting (eg,0.1s
)
You can shorthand them:
transition: property duration timing-function delay;
Best Practices
- Use
transform
andopacity
for best performance—they don't trigger layout or paint. - Avoid transitioning
width
,height
,margin
, orleft/top
—they cause reflows. - Always define a starting state (eg,
opacity: 1
) so the browser knows where to transition from.
CSS Animations: Full Control with Keyframes
Animations go beyond simple hover effects. They let you define complex, multi-step sequences using @keyframes
.
How They Work
You define named keyframe rules that specify styles at different points (0%, 50%, 100%), then assign that animation to an element.
Example: Fade and Slide In
@keyframes slideIn { 0% { opacity: 0; transform: translateX(-20px); } 100% { opacity: 1; transform: translateX(0); } } .animate-me { animation: slideIn 0.5s ease-out; }
Animation Properties
-
animation-name
: Name of the@keyframes
rule -
animation-duration
: How long one cycle takes -
animation-timing-function
: Speed curve -
animation-delay
: Wait before starting -
animation-iteration-count
: How many times (eg,3
,infinite
) -
animation-direction
:normal
,reverse
,alternate
-
animation-fill-mode
: What styles apply before/after (forwards
,backwards
,both
) -
animation-play-state
:running
(default) orpaused
Shortand:
animation: name 2s ease-in 1s infinite alternate both;
Use Cases
- Loading spinners
- Entrance effects (fading in elements on page load)
- Repeating micro-interactions
- Complex sequences with multiple transforms
Choosing Between Transitions and Animations
Not sure which to use? Here's a quick breakdown:
Use transitions when:
- You want a simple, reversible change (hover, focus, class toggle)
- The animation only has two states (start and end)
- You want something triggered by user interaction
Use animations when:
- You need more than two key points (eg, bounce, pulse, loop)
- You want automatic playback (on load, without interaction)
- You need infinite looping or complex timing
- You're creating sequences independent of state changes
Performance Tips and Gotchas
Stick to
transform
andopacity
These properties are optimized by the browser (often handled by the GPU). Animatingtop
,left
,width
, orheight
forces layout reccalculations and can cause jank.Use
will-change
sparingly
It hints to the browser that an element will be animated:.moving-element { will-change: transform; }
But overuse can hurt performance—only apply it when needed.
Prefer
transform: translate()
overtop/left
Instead of:top: 10px;
Use:
transform: translateY(10px);
Avoid animating
box-shadow
orfilter
on large elements
These can be expensive. If you must, test performance on lower-end devices.Use
prefers-reduced-motion
for accessibility
Respect users who want less motion:@media (prefers-reduced-motion: reduce) { * { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; } }
Bonus: Combining Transitions and Animations
Sometimes you need both. For example, a modal that:
- Animates in with a keyframe animation on open
- Has a close button that smoothly fades out on hover using a transition
.modal { opacity: 0; animation: fadeIn 0.3s forwards; } .close-btn { opacity: 0.7; transition: opacity 0.2s; } .close-btn:hover { opacity: 1; }
This layered approach keeps interacts smooth and intentional.
Basically, transitions are for simple, interactive changes. Animations are for complex, self-contained sequences. Use the right tool, optimize for performance, and always consider accessibility. With these in your toolkit, your UIs will feel polished and responsive—no JavaScript required.
The above is the detailed content of The Complete Guide to CSS Transitions and Animations. 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)

React itself does not directly manage focus or accessibility, but provides tools to effectively deal with these issues. 1. Use Refs to programmatically manage focus, such as setting element focus through useRef; 2. Use ARIA attributes to improve accessibility, such as defining the structure and state of tab components; 3. Pay attention to keyboard navigation to ensure that the focus logic in components such as modal boxes is clear; 4. Try to use native HTML elements to reduce the workload and error risk of custom implementation; 5. React assists accessibility by controlling the DOM and adding ARIA attributes, but the correct use still depends on developers.

Shallowrenderingtestsacomponentinisolation,withoutchildren,whilefullrenderingincludesallchildcomponents.Shallowrenderingisgoodfortestingacomponent’sownlogicandmarkup,offeringfasterexecutionandisolationfromchildbehavior,butlacksfulllifecycleandDOMinte

StrictMode does not render any visual content in React, but it is very useful during development. Its main function is to help developers identify potential problems, especially those that may cause bugs or unexpected behavior in complex applications. Specifically, it flags unsafe lifecycle methods, recognizes side effects in render functions, and warns about the use of old string refAPI. In addition, it can expose these side effects by intentionally repeating calls to certain functions, thereby prompting developers to move related operations to appropriate locations, such as the useEffect hook. At the same time, it encourages the use of newer ref methods such as useRef or callback ref instead of string ref. To use Stri effectively

Create TypeScript-enabled projects using VueCLI or Vite, which can be quickly initialized through interactive selection features or using templates. Use tags in components to implement type inference with defineComponent, and it is recommended to explicitly declare props and emits types, and use interface or type to define complex structures. It is recommended to explicitly label types when using ref and reactive in setup functions to improve code maintainability and collaboration efficiency.

Server-siderendering(SSR)inNext.jsgeneratesHTMLontheserverforeachrequest,improvingperformanceandSEO.1.SSRisidealfordynamiccontentthatchangesfrequently,suchasuserdashboards.2.ItusesgetServerSidePropstofetchdataperrequestandpassittothecomponent.3.UseSS

WebAssembly(WASM)isagame-changerforfront-enddevelopersseekinghigh-performancewebapplications.1.WASMisabinaryinstructionformatthatrunsatnear-nativespeed,enablinglanguageslikeRust,C ,andGotoexecuteinthebrowser.2.ItcomplementsJavaScriptratherthanreplac

Vite or VueCLI depends on project requirements and development priorities. 1. Startup speed: Vite uses the browser's native ES module loading mechanism, which is extremely fast and cold-start, usually completed within 300ms, while VueCLI uses Webpack to rely on packaging and is slow to start; 2. Configuration complexity: Vite starts with zero configuration, has a rich plug-in ecosystem, which is suitable for modern front-end technology stacks, VueCLI provides comprehensive configuration options, suitable for enterprise-level customization but has high learning costs; 3. Applicable project types: Vite is suitable for small projects, rapid prototype development and projects using Vue3, VueCLI is more suitable for medium and large enterprise projects or projects that need to be compatible with Vue2; 4. Plug-in ecosystem: VueCLI is perfect but has slow updates,

Immutable updates are crucial in React because it ensures that state changes can be detected correctly, triggering component re-rendering and avoiding side effects. Directly modifying state, such as push or assignment, will cause React to be unable to detect changes. The correct way to do this is to create new objects instead of old objects, such as updating an array or object using the expand operator. For nested structures, you need to copy layer by layer and modify only the target part, such as using multiple expansion operators to deal with deep attributes. Common operations include updating array elements with maps, deleting elements with filters, adding elements with slices or expansion. Tool libraries such as Immer can simplify the process, allowing "seemingly" to modify the original state but generate new copies, but increase project complexity. Key tips include each
