Building Animated Web Interfaces
Default stack: semantic HTML + CSS custom properties + CSS transitions/keyframes for simple motion, Web Animations API or GSAP for sequenced/scroll-driven motion. No framework required.
Drop-in motion foundation (put at the top of every project):
CSS:root { /* Easing */ --ease-out: cubic-bezier(0.22, 1, 0.36, 1); /* entrances, most UI */ --ease-in-out: cubic-bezier(0.65, 0, 0.35, 1); /* movement across screen */ --ease-in: cubic-bezier(0.64, 0, 0.78, 0); /* exits only */ --ease-spring: cubic-bezier(0.34, 1.56, 0.64, 1); /* playful overshoot, use sparingly */ /* Durations */ --dur-instant: 100ms; /* press feedback */ --dur-fast: 180ms; /* hover, toggles */ --dur-base: 320ms; /* menus, cards, modals */ --dur-slow: 600ms; /* page/section reveals */ --stagger: 60ms; } /* Accessibility is non-negotiable */ @media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; scroll-behavior: auto !important; } }
Scroll-reveal pattern (IntersectionObserver, no library):
CSS.reveal { opacity: 0; transform: translateY(24px); transition: opacity var(--dur-slow) var(--ease-out), transform var(--dur-slow) var(--ease-out); transition-delay: calc(var(--i, 0) * var(--stagger)); } .reveal.is-visible { opacity: 1; transform: none; }
JavaScriptconst io = new IntersectionObserver((entries) => { entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add('is-visible'); io.unobserve(e.target); } }); }, { threshold: 0.15, rootMargin: '0px 0px -8% 0px' }); document.querySelectorAll('.reveal').forEach((el, i) => { el.style.setProperty('--i', i % 6); io.observe(el); });
Follow these stages in order. Do not skip ahead to polish before the thing works.
Progress:
- [ ] 1. Gather references
- [ ] 2. Sketch (structure + motion plan)
- [ ] 3. Make it work (functional build)
- [ ] 4. Finish it (full visual + motion implementation)
- [ ] 5. Find bugs (audit)
- [ ] 6. Compare against references AND the original prompt
- [ ] 7. Polish
- [ ] 8. Deliver
1. Gather references
- Identify 2-4 reference points: real sites/products, or well-known UI patterns that match the requested feel (e.g., Linear for crisp micro-motion, Apple product pages for scroll storytelling, Stripe for gradient/depth, Awwwards-style sites for editorial motion).
- For each reference, write down in one line: what specifically to borrow (timing, layout rhythm, easing feel, hover behavior). Do not copy assets or code verbatim; extract principles.
- If the user supplied references or screenshots, they override your own picks.
- Restate the user's prompt as a checklist of explicit requirements. This checklist is used again in step 6.
2. Sketch
Before writing code, output a brief plan:
- Layout skeleton: sections/components in order (ASCII or bullet outline).
- Motion map: a table of element → trigger → effect → duration/easing.
- Design tokens: colors, type scale, spacing scale, radii, shadows.
- Motion hierarchy: pick ONE hero moment (the signature animation); everything else supports it quietly.
Example motion map:
| Element | Trigger | Effect | Timing |
|---|---|---|---|
| Hero headline | Page load | Line-by-line rise + fade | 600ms, ease-out, 80ms stagger |
| Nav links | Hover | Underline scales from left | 180ms, ease-out |
| Cards | Enter viewport | Fade + translateY(24px) | 600ms, stagger 60ms |
| CTA button | Press | Scale 0.97 | 100ms |
3. Make it work
- Build semantic HTML first (
header,nav,main,section,button,a). Interactive things are real<button>/<a>, never clickable<div>s. - Implement layout and static styles with no animation. Verify responsive behavior at 360px, 768px, 1280px+.
- Add the core interaction logic (menu toggles, tabs, modals) with state classes or
data-attributes. Confirm functionality works with animations disabled. - Only then layer motion on top.
4. Finish it
Implement the motion map from step 2 using the technique selection guide below. Complete all sections, states (default, hover, focus-visible, active, disabled, loading, empty, error), and breakpoints.
5. Find bugs
Run this audit explicitly and fix what fails:
- No layout shift (CLS): animated elements reserve space; images have width/height or aspect-ratio
- Only
transformandopacityanimated (notop/left/width/height/margin) unless unavoidable - No flash of unstyled/hidden content on load (initial hidden states set in CSS, not JS-after-paint)
- Hover effects don't fire on touch (wrap in
@media (hover: hover)) - Keyboard: all interactive elements reachable, visible
:focus-visiblering, modals trap focus and close on Esc -
prefers-reduced-motionrespected (see Quick Start block) - No horizontal scroll at any width (
overflow-xnot hiding a bug) - Animations don't restart/jitter on rapid hover in/out or resize
- Z-index conflicts, sticky/fixed elements overlapping content
- Event listeners cleaned up; scroll handlers are passive/throttled or use IntersectionObserver
- No console errors; works in Chromium, Firefox, Safari (check
backdrop-filter,dvh,:has()support) - 60fps feel: no long main-thread tasks during animation
6. Compare against references and prompt
- Go through the requirement checklist from step 1 line by line. Mark each ✅ / ❌ and fix every ❌.
- Compare to references on: spacing rhythm, type hierarchy, motion timing, color contrast, overall "feel". Note deltas and close the biggest ones.
- Confirm nothing was added that the user didn't ask for if it changes the brief's intent.
7. Polish
Apply the polish pass (see Best Practices > Polish Checklist): timing tweaks, easing consistency, micro-details, contrast, alignment, text rendering.
8. Deliver
Send complete, runnable code (single file unless the project warrants splitting). Include a 3-6 line summary: what was built, the signature animation, any tokens the user can tweak (e.g., --dur-base), and any known limitations. No long explanations.
| Need | Use | Why |
|---|---|---|
| Hover, focus, toggles, simple state change | CSS transition | Cheapest, declarative |
| Looping/ambient motion, loaders, skeletons | CSS @keyframes | No JS, GPU friendly |
| Sequenced timelines, complex choreography | GSAP (gsap.timeline) or Web Animations API | Precise control, easy stagger |
| Reveal on scroll | IntersectionObserver + CSS classes | Simple, performant |
| Scroll-linked (parallax, progress, pinning) | CSS animation-timeline: scroll()/view() where supported, else GSAP ScrollTrigger | Native when possible |
| Page/view transitions | View Transitions API (document.startViewTransition) with fallback | Smooth, minimal code |
| Layout changes (reorder, expand) | FLIP technique (First-Last-Invert-Play) | Animates layout via transform |
| Physics/gesture-driven | Spring-based (Framer Motion in React, or hand-rolled spring) | Natural feel |
| Text effects | Split into spans (line/word), animate with stagger; keep original text in aria-label | Preserves accessibility |
| Complex vector/illustrated motion | SVG + CSS/GSAP, or Lottie for designer-exported assets | Scalable |
| 3D/shader/particles | Three.js / WebGL, only if the brief demands it | Heavy; justify it |
Prefer the lightest tool that achieves the effect. If using GSAP, load from a CDN and gsap.registerPlugin(ScrollTrigger) explicitly.
Example 1: Input: "Make this button feel premium on hover and click." Output:
CSS.btn { position: relative; padding: .9em 1.6em; border-radius: 12px; background: var(--accent); color: #fff; border: 0; transition: transform var(--dur-fast) var(--ease-out), box-shadow var(--dur-fast) var(--ease-out), background-color var(--dur-fast); will-change: transform; } @media (hover: hover) { .btn:hover { transform: translateY(-2px); box-shadow: 0 10px 24px -8px color-mix(in srgb, var(--accent) 60%, transparent); } } .btn:active { transform: translateY(0) scale(.97); transition-duration: var(--dur-instant); } .btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
Example 2:
Input: "Animated hero headline that types in line by line."
Output approach: wrap each line in <span class="line"><span class="line-inner">…</span></span>; .line { overflow: hidden }; .line-inner { display:inline-block; transform: translateY(110%); animation: rise 800ms var(--ease-out) forwards; animation-delay: calc(var(--i) * 90ms); } with @keyframes rise { to { transform: none } }. Set --i per line in JS or inline. Reduced-motion block collapses it to instant.
Example 3: Input: "Smooth page transition between two views, no framework." Output approach:
JavaScriptfunction navigate(updateDOM) { if (!document.startViewTransition) return updateDOM(); document.startViewTransition(updateDOM); }
CSS::view-transition-old(root) { animation: fade-out var(--dur-base) var(--ease-in) both; } ::view-transition-new(root) { animation: fade-in var(--dur-base) var(--ease-out) both; }
Example 4:
Input: "Skeleton loader for a card list."
Output approach: gray blocks with a moving gradient: background: linear-gradient(90deg, var(--bg-2) 25%, var(--bg-3) 50%, var(--bg-2) 75%); background-size: 200% 100%; animation: shimmer 1.4s linear infinite; Reserve exact card dimensions to prevent layout shift.
Motion principles
- Purpose first: every animation must guide attention, give feedback, show relationship, or add deliberate delight. If it does none, cut it.
- Timing: micro-feedback 100-200ms, standard UI 250-400ms, large/hero 500-900ms. Nothing over 1s for UI chrome. Exits are faster than entrances (~70%).
- Easing: ease-out for things entering, ease-in for things leaving, ease-in-out for moving across the screen. Never use
linearexcept for continuous loops (spinners, shimmer, marquees). - Stagger groups by 40-80ms, cap total stagger under ~600ms (limit staggered items or use modulo).
- One signature moment per view; everything else is subtle. Restraint reads as quality.
- Consistency: reuse the same tokens everywhere. Same element type = same motion.
- Origin: scale/rotate from a logical
transform-origin(dropdowns from their trigger, tooltips from their arrow).
Visual comfort
- Maintain text contrast ≥ 4.5:1 (body), ≥ 3:1 (large text/UI). Check animated/gradient backgrounds too.
- Use a consistent spacing scale (4/8px base) and a modular type scale;
clamp()for fluid type:font-size: clamp(2.25rem, 1.2rem + 4vw, 5rem). - Generous whitespace; avoid more than ~2 typefaces. Line length 55-75ch for body text.
- Avoid motion that causes discomfort: no large parallax on whole-viewport backgrounds, no flashing >3 times/second, no auto-playing looping motion near reading text without a pause option.
- Depth via layered soft shadows and subtle borders rather than heavy drop shadows.
- Dark themes: avoid pure
#000on pure#ffftext; use off-black (#0b0b0f) and off-white (#ececf1).
Stable, clean code
- Design tokens in
:rootcustom properties; no magic numbers scattered. - BEM-ish or utility-consistent naming; state via classes (
is-open) ordata-state. - Animate with
transform/opacity; usewill-changeonly on elements about to animate, and remove after. - Use
@media (hover: hover),@media (prefers-reduced-motion),@media (prefers-color-scheme)appropriately. - Use
dvhinstead ofvhfor full-height mobile sections (min-height: 100dvh). - Clean up:
removeEventListener, kill GSAP timelines/ScrollTriggers on teardown, disconnect observers. - Progressive enhancement: content visible and usable if JS fails; JS adds the
jsclass to<html>so hidden-initial-states only apply when JS runs. - Keep it to one clear file structure:
<style>with tokens → base → components → utilities → motion;<script>at end, modular functions.
Polish Checklist
- Easing and duration tokens used everywhere (no stray values)
- Hover/focus/active states all present and consistent
- Alignment and optical spacing checked (icons centered with text, consistent padding)
-
text-wrap: balanceon headings,text-wrap: prettyon paragraphs -
-webkit-font-smoothing: antialiased; fonts preloaded withfont-display: swap - Custom
::selectioncolor, styled scrollbar if appropriate,scroll-behavior: smooth(guarded by reduced-motion) - Subtle details: noise/grain overlay, gradient borders, inner highlights, cursor states
- Loading, empty, and error states designed, not default
- Image/video lazy-loading and proper sizing
- Final perf sanity: Lighthouse-style mental check (no render-blocking junk, no giant unoptimized assets)
- Animating layout properties (
width,height,top,left,margin) causing jank; usetransformor FLIP. - Everything animates at once: no hierarchy, visual noise. Pick a hero moment and subordinate the rest.
- Too slow or too bouncy: long durations (>800ms on UI) and spring overshoot everywhere feel amateur.
- Ignoring
prefers-reduced-motionor hover-only interactions that break on touch. - Hidden-until-JS content causing flashes or blank pages when scripts fail.
- Scroll hijacking: overriding native scroll speed/direction frustrates users; enhance, don't replace.
- Using
transition: all: causes unintended property animations and perf hits; list properties explicitly. - Fixed pixel sizes everywhere: breaks responsiveness; use
rem,%,clamp(), grid/flex. - Skipping the bug audit and reference comparison: shipping after "it works" instead of after verification.
- Over-engineering: pulling in heavy libraries (Three.js, large animation suites) for effects CSS can do.
- Inaccessible text animation: splitting text into spans without preserving a readable
aria-label. - Delivering partial code or placeholders ("add your logic here"); always deliver complete, runnable output.
If the project grows beyond ~500 lines, split into
tokens.css,components.css,motion.css, andmain.js, and reference them from the HTML.