6 min read
Framer Motion: animating height transitions in React
Collapsible content needs a height that fits what is inside. This Framer Motion setup measures the content and sets the duration from its size.
The Height Animation Problem
Animating height transitions is notoriously tricky in CSS. Unlike opacity or transforms, you can't simply transition from height: 0 to height: auto. The browser needs concrete values to interpolate between:
/* This doesn't work */
.collapsible {
height: 0;
transition: height 0.3s;
}
.collapsible.open {
height: auto; /* Can't animate to 'auto' */
}
Common workarounds involve JavaScript to calculate heights, max-height hacks that create awkward timing, or fixed heights that break with dynamic content. None of these are ideal. Two CSS-only routes exist now: transitioning grid-template-rows from 0fr to 1fr (animatable in Chrome 107, Firefox 66 and Safari 16 and newer), and interpolate-size: allow-keywords, which lets height: auto animate directly. The second one works in Chrome and Edge 129 and newer. Firefox has not shipped it and Safari has it only in preview (MDN). The component below is for when you want Framer Motion's variants and a duration scaled to the content.
For expandable sections, accordions, dropdowns, or any collapsible UI, we need smooth height transitions that work with dynamic content of any size.
Solution
Framer Motion combined with the react-use library's useMeasure hook gives us a clean solution. Framer Motion animates the height between 0 and auto and resolves auto itself. We measure the content only to set the duration: taller content gets a longer animation.
Framer Motion is now published as motion, and you import from motion/react. The API used here is the same.
import type { ReactNode } from 'react'
import { useMeasure } from 'react-use'
import { motion, type Easing, type Variants } from 'framer-motion'
interface AnimateHeightProps {
isVisible: boolean
ease?: Easing
duration?: number
className?: string
variants?: Variants
children: ReactNode
}
const defaultVariants: Variants = {
open: { opacity: 1, height: 'auto' },
collapsed: { opacity: 0, height: 0 },
}
export const AnimateHeight = ({
isVisible,
ease = 'easeInOut',
duration,
className,
variants = defaultVariants,
children,
}: AnimateHeightProps) => {
const [ref, { height }] = useMeasure<HTMLDivElement>()
return (
<motion.div
className={['overflow-hidden', className].filter(Boolean).join(' ')}
initial={isVisible ? 'open' : 'collapsed'}
animate={isVisible ? 'open' : 'collapsed'}
inert={!isVisible}
inherit={false}
variants={variants}
transition={{
ease,
duration: duration ?? getAutoHeightDuration(height) / 1000,
}}
>
<div ref={ref}>{children}</div>
</motion.div>
)
}
/**
* Get the duration of the animation depending upon
* the height provided.
* Copied unchanged from Material UI v5 (MIT License):
* https://github.com/mui/material-ui/blob/v5.x/packages/mui-material/src/styles/createTransitions.js
* Copyright (c) 2014 Call-Em-All
* @param {number} height of container
*/
const getAutoHeightDuration = (height: number) => {
if (!height) return 0
const constant = height / 36
return Math.round((4 + 15 * constant ** 0.25 + constant / 5) * 10)
}
How It Works
useMeasure Hook: Tracks the rendered height of the content with a ResizeObserver. The measured height is used for one thing: the duration. It is not the animation target, because Framer Motion animates to height: 'auto' and works out the pixels itself.
Motion Variants: Define two states:
open- Full height with opacity 1collapsed- Zero height with opacity 0
Dynamic Duration: The getAutoHeightDuration function calculates animation timing based on content height. Taller content gets longer animations, preventing jarring fast transitions for large sections.
overflow-hidden: Critical for the effect - hides content as the container shrinks to zero height. A className you pass is merged with it, so it never replaces it.
inert: Collapsed content has height 0 and opacity 0, but it stays in the tab order and the accessibility tree, so Tab can land on a hidden button, link or input. inert removes it from both while the section is collapsed. A boolean inert prop needs React 19.
inherit=false: Prevents inheriting animation variants from parent motion components, keeping this animation independent.
The Duration Formula
The getAutoHeightDuration function deserves attention. It is Material UI's function of the same name, from its transitions code (source, v5, MIT License). The component uses it unchanged. MUI's current version also caps the result at 3000ms.
const getAutoHeightDuration = (height: number) => {
if (!height) return 0
const constant = height / 36
return Math.round((4 + 15 * constant ** 0.25 + constant / 5) * 10)
}
This formula creates a non-linear relationship between height and duration:
- Small heights (50px): ~206ms
- Medium heights (200px): ~281ms
- Large heights (500px): ~357ms
- Extra large (1000px): ~440ms
Breaking Down the Math
Let's dissect that return statement: Math.round((4 + 15 * constant ** 0.25 + constant / 5) * 10)
Step 1: Normalize the height
const constant = height / 36
This converts pixels to a normalized scale. For example, 360px becomes 10, making the math more manageable. The 36 is Material UI's choice, not a law. Change it if your sections need a different curve.
Step 2: Three components create the curve
The formula has three parts that add together:
-
Base duration:
4- The constant term, 40ms after × 10
- It is not the minimum: the fourth-root term rises steeply near zero, so at 1px the result is already 101ms
-
Diminishing growth:
15 * constant ** 0.25- The
** 0.25is a fourth root, creating sublinear growth - This is the key: doubling height doesn't double duration
- Prevents massive elements from having sluggish animations
- The
-
Linear component:
constant / 5- Adds some proportional scaling
- Balances out the diminishing returns from component 2
Step 3: Scale to milliseconds
Math.round((...) * 10)
Multiply by 10 to convert to milliseconds and round for clean values.
Why This Curve?
The fourth root (** 0.25) is the secret sauce. Compare linear vs fourth-root scaling:
| Height | Linear (height/2) | Fourth Root (formula) |
|---|---|---|
| 100px | 50ms | ~239ms |
| 400px | 200ms | ~336ms |
| 1600px | 800ms | ~516ms |
A plain height / 2 rule makes a 100px section flash by in 50ms and a 1600px one crawl for 800ms. The formula is slower than that for small heights and faster for large ones, so a 1600px section takes a bit over half a second.
For extra crispy effect you could clamp this value to a range.
Math.min(Math.max(calculated, 150), 400)
The bounds are a choice. With 150 and 400, the floor applies below 11px of content and the cap from 740px.
At the end of day, you can override this by passing a fixed duration prop when you need consistent timing across all heights.
Practical Usage
Simple accordion:
const Accordion = ({ title, content }: { title: string; content: ReactNode }) => {
const [isOpen, setIsOpen] = useState(false)
return (
<div>
<button aria-expanded={isOpen} onClick={() => setIsOpen(!isOpen)}>
{title}
</button>
<AnimateHeight isVisible={isOpen}>
<div className='p-4'>{content}</div>
</AnimateHeight>
</div>
)
}
Custom animation variants:
<AnimateHeight
isVisible={showDetails}
variants={{
open: {
opacity: 1,
height: 'auto',
y: 0,
},
collapsed: {
opacity: 0,
height: 0,
y: -8,
},
}}
>
<DetailsList />
</AnimateHeight>
Fixed duration for consistent timing:
<AnimateHeight isVisible={expanded} duration={0.2} ease='easeOut'>
{children}
</AnimateHeight>
Why This Approach Works
Automatic measurement: No manual height calculations needed. The duration follows the height of the content.
Smooth animations: Unlike max-height hacks, the animation duration matches the actual height transition.
Flexible: Override defaults when needed while keeping sensible behavior out of the box.
Dynamic content: An open container sits at height: auto, so it follows its content at once: when the content grows or shrinks, the container jumps to the new height in one frame. Only opening and closing animate, and the next open or close uses the new height for its duration.
Performance Considerations
While this approach is generally performant, be aware:
Height animations trigger layout recalculation: Unlike transforms, animating height is not GPU-accelerated. For numerous simultaneous animations, this can impact performance.
Measurement overhead: useMeasure uses ResizeObserver, which is efficient but adds overhead. For hundreds of collapsible items, consider virtualization.
Reduced motion: Wrap the app in <MotionConfig reducedMotion="user"> to respect prefers-reduced-motion. Framer Motion then skips the height animation for visitors who asked for less motion, and the height jumps at once, while the opacity fade still runs.
Alternative for performance-critical cases: If you need many height animations, consider animating scaleY transform instead:
// More performant but content gets squished
<motion.div
style={{ transformOrigin: 'top' }}
animate={{ scaleY: isOpen ? 1 : 0 }}
/>
The tradeoff is that scaleY squishes content during animation, while height animations maintain readable content throughout.
Comparison with AnimatePresence
This component differs from the AnimateAppearance pattern:
| Feature | AnimateHeight | AnimatePresence |
|---|---|---|
| Use case | Expanding/collapsing sections | Mounting/unmounting components |
| Content in DOM | Always present, just hidden | Removed from DOM when hidden |
| Animation type | Height + opacity | Position/scale + opacity |
| Performance | Layout recalc on animation | GPU-accelerated transforms |
Use AnimateHeight when content should remain in the DOM (for SEO, form state, etc.) and you want vertical expand/collapse. Use AnimatePresence when components are truly conditional and should be unmounted.
Common Use Cases
FAQ accordions:
{
faqs.map(faq => (
<AnimateHeight key={faq.id} isVisible={openId === faq.id}>
<Answer>{faq.answer}</Answer>
</AnimateHeight>
))
}
Filter panels:
<AnimateHeight isVisible={showFilters}>
<FilterGroup />
</AnimateHeight>
Form sections:
<AnimateHeight isVisible={paymentMethod === 'card'}>
<CreditCardFields />
</AnimateHeight>
Fields inside a collapsed section are still part of the form: they submit, and a required one still blocks submission. Disable them or unmount them when the section is hidden.
Conclusion
The AnimateHeight component solves one of CSS's most annoying limitations by combining Framer Motion's animation capabilities with a measured content height that sets the duration. By measuring the content and scaling the duration to its size, we get:
- Smooth height transitions without CSS hacks
- A duration that adapts to content size
- Customizable timing when needed
- Clean, reusable animation logic
Next time you need a collapsible section, skip the CSS gymnastics and reach for this component. Your users will appreciate the smooth, professional transitions.