CSS Animation Assistant
Description
Specialized assistant for implementing CSS animations in the DWP Hours Tracker frontend, ensuring compliance with performance, accessibility, and maintainability standards. This skill guides the creation of efficient, hardware-accelerated animations that enhance user experience without introducing technical debt.
Trigger
Activate this skill when users request:
- Creating new CSS animations or transitions
- Optimizing existing animations for performance
- Implementing accessibility-compliant animations
- Adding mobile-specific animation features
- Reviewing or refactoring animation code
Response Pattern
Follow this step-by-step approach when implementing CSS animations:
- Assess Requirements: Analyze the animation purpose, target elements, and user interaction context
- Property Selection: Ensure only hardware-accelerated properties (
transform,opacity,filter) are animated - Performance Optimization: Apply
will-changestrategically and use GPU acceleration techniques - Accessibility Implementation: Add
prefers-reduced-motionsupport and ARIA attributes as needed - Mobile Considerations: Optimize for touch inputs and reduce complexity on mobile devices
- Code Structure: Use CSS variables, modular keyframes, and utility classes for maintainability
- Testing & Validation: Test across devices, validate with performance tools, and ensure graceful degradation
- Documentation: Add code comments explaining animation purpose, performance impact, and accessibility features
Lessons Learned
Hard-won patterns from real implementations in this project:
Multi-phase animations (carousel, slide-in/out)
- Use inline styles, not CSS classes for sequenced animation phases. Class-based approaches suffer from specificity conflicts and unreliable style flushing between phases.
- Force synchronous reflow with
void element.offsetHeightbetween phases to guarantee the browser commits an intermediate position before re-enabling transitions. DoublerequestAnimationFrameis not reliable for this. - Filter
transitionendbye.propertyName(e.g.,=== "transform") to prevent double-firing when animating multiple properties (transform+opacity). - Guard against overlapping animations with an
isAnimatingflag checked at entry and cleared on completion. - Always add a
setTimeoutfallback after the animation duration (+50ms buffer) that runs the same completion logic astransitionend. Thetransitionendevent will not fire if the element is destroyed mid-animation (e.g., by a re-render) or in test environments without CSS transition support. Without a fallback,isAnimatinggets stucktrueand the component deadlocks. - Allow re-toggle during animation — instead of
if (isAnimating) return, call afinalizeAnimation()helper that clears the fallback timer, removes inline styles, and resets the flag, then proceed with the new action. This prevents the component from becoming unresponsive to rapid user clicks. - Deduplicate completion logic — extract a single
onCompleteclosure shared by both thetransitionendhandler and thesetTimeoutfallback. Have it clear the timer, remove the event listener, clean up styles, and reset state, so the first to fire wins and the second is a no-op. - Clean up inline styles after animation completes — remove
willChange,transition,transform, andopacityto avoid stale state.
Menu and dropdown animations
- Prefer slide (motion) over fade for menu reveal/hide. Slide-down (
translateY) provides stronger spatial context than opacity transitions alone. Combine with a subtle opacity change for polish, but the motion must be the primary effect. - Use
translateY(-8px)as the hidden position for dropdown menus — small enough to feel natural, large enough to be perceptible. - Decelerate on open, accelerate on close — use a decelerate easing (
cubic-bezier(0, 0, 0.2, 1)) when revealing and an accelerate easing (cubic-bezier(0.4, 0, 1, 1)) when hiding, so elements feel like they arrive gently and leave quickly.
Accessibility
- Always provide a
prefersReducedMotion()check that skips animation entirely (instant state change) rather than just shortening duration. - Query
window.matchMedia("(prefers-reduced-motion: reduce)")at animation time, not at component init, so runtime preference changes are respected.
innerHTML re-render destroys scroll context on mobile
- Never call
requestUpdate()on a parent component to enter/exit edit mode when an animated child component handles its own card→editor transition. The parent'srenderTemplate()replaces its entire shadow DOM viainnerHTML, which destroys the child element (and its scroll position). On mobile single-column layouts the page height briefly collapses to near-zero, causing the browser to clampwindow.scrollYto 0. By the time the child is recreated and populated, the user is staring at the top of the page. - Set properties directly on the existing child element instead of re-rendering the parent. For example, set
list.editingEmployeeId = idon the live<employee-list>rather than callingthis.requestUpdate()on<admin-employees-page>. The child'sattributeChangedCallbackthen runstransitionCardToEditor()with the DOM intact and scroll preserved. - The actual scroll container matters —
.employee-gridhasoverflow-y: autoandflex: 1, but its parent chain doesn't establish a fixed-height constraint, soscrollHeight === clientHeight(it's never scrollable). The real scroll container iswindow. Always usewindow.scrollBy()andgetBoundingClientRect()for position correction, nevergrid.scrollTop. - Use
getBoundingClientRect().topbefore and after re-render to calculate drift. After the synchronousrequestUpdate()(innerHTML replacement), read the editor'sgetBoundingClientRect().top— this forces a layout before the browser paints, making thewindow.scrollBy(0, drift)correction invisible to the user. Measured drift is <1px. - Cancel and form-cancel handlers need the same treatment — when exiting inline edit mode, clear
editingEmployeeIdon the existing child component rather than re-rendering the parent. Distinguish between "was inline editing" vs "was showing add form" to decide whether a parent re-render is needed.
Touch swipe isolation on mobile (Android Chrome)
Touch-driven swipe navigation (e.g., swiping a calendar to change months) must not drag the page. The solution depends on the component's scroll context.
- Prefer CSS
touch-action: pan-yon the swipe container. This tells the browser to handle vertical panning natively (page scrolls normally) and leave horizontal gestures to JavaScript. It's declarative, zero-runtime-cost, and works reliably on Android Chrome hardware — notouchmovehandler needed. - Do NOT combine
overscroll-behavior: containwithoverflow: hidden. On an element that has no scrollable content,overscroll-behavior: containtells the browser "this element is at its scroll boundary, don't chain to the parent." On real Android Chrome hardware, this kills vertical page scrolling entirely when touching the element. Chrome DevTools device emulation does not reproduce this — always test on real hardware. - The
touchmove+preventDefault()approach is a power tool, not a default. Registering a non-passivetouchmovehandler to callpreventDefault()during horizontal swipes works but forces Chrome to block all native scrolling until the JS handler runs and determines gesture direction. This adds input latency and temporarily freezes vertical scrolling. Make it opt-in via apreventPageScrolloption (seeSwipeNavigationOptions), and document that CSStouch-action: pan-yis the preferred alternative. - Swipe detection needs only
touchstart+touchendfor direction and threshold. ThesetupSwipeNavigationhelper records start coordinates ontouchstart, computes delta ontouchend, and fires the navigation callback if horizontal distance exceeds the threshold and dominates vertical distance. Notouchmovetracking needed for the core gesture. - Grid
minmax()can overflow narrow viewports. A grid likerepeat(auto-fill, minmax(40ch, 1fr))can push cards past the right edge on a Pixel 7 (412 CSS px). Useminmax(min(40ch, 100%), 1fr)to cap the minimum at the container width. - DevTools emulation ≠ real device. Touch event handling, DPR subpixel rounding, and overscroll chaining all behave differently on real Android Chrome. Always validate touch interactions on hardware via
chrome://inspectremote debugging.
Examples
Common user queries that should trigger this skill:
- "Add a fade-in animation to the PTO calendar"
- "Optimize the loading spinner animation for better performance"
- "Make the employee form slide in smoothly"
- "Ensure animations work with reduced motion preferences"
- "Create a swipe gesture animation for mobile"
Additional Context
This skill integrates with the project's CSS Animation Policy and web components architecture. All animations must align with the atomic CSS design principles and use tokens from tokens.css for durations and easings. Reference the project's css.ts pattern for component-specific styles and ensure animations are tested in both Vitest (unit) and Playwright (E2E) environments.