Animate height to auto
One CSS line lets height transition from 0 to auto.
Josh W. Comeau@joshwcomeau.com๐ A long-requested CSS feature is the ability to transition height between a known value (`height: 20rem`) and a derived one (`height: auto`). A new global CSS property makes this possible now. ๐ html { interpolate-size: allow-keywords; } More info in thread ๐งต
Josh W. Comeau@joshwcomeau.com๐ I just updated by CSS Reset to include a handy new declaration: html { interpolate-size: allow-keywords; } This rule allows us to animate height from "0px" to "auto", perfect for accordions and other collapsible UI. โจ Learn more in my blog post about it: www.joshwcomeau.com/css/custom-c...
1 ยท Height to auto
Open and close each item. Watch the motion time.
No opt-in: snapsBad
height: 0 โ autoMotionโinterpolate-sizeGood
allow-keywordsMotionโNot supported here: it snapshtml {
interpolate-size: allow-keywords;
}
.panel {
height: 0;
overflow: clip;
transition: height 250ms var(--ease-out);
}
.panel[data-open] { height: auto; }
2 ยท The max-height hack
Open and close the short item in each.
max-height: 600pxBad
max-heightMotionโheight: autoGood
height: autoMotionโ/* hack: animates to a guess, so speed and delay are wrong */
.panel { max-height: 0; transition: max-height 250ms; }
.panel[data-open] { max-height: 600px; }
/* real height: the transition ends exactly at the content */
.panel[data-open] { height: auto; }
Why it matters, pros and cons
Why it matters
Browsers could not interpolate to auto. One inherited property now lets height, width and more animate to keywords.
Pros
- Plain CSS: no measuring, no ResizeObserver, no max-height guess.
- Speed and easing stay the same whatever the content length.
- Collapse starts moving at once instead of after a hidden delay.
Cons
- Unsupported browsers snap open, so treat the motion as an extra.
- Content below the panel moves each frame, which is layout work.
- It affects every height: auto on the page unless you scope the property.