Enable a real CSS
transition to and from
height:auto by filling in the natural height of the element during the transition with a bit of jQuery.
There are any number of potential use cases for a transition to and from
height:auto, for example a simple expanding/collapsing menu:
Along with using CSS to animate the transition, one of the benefits of this technique is that the HTML and CSS are exactly as they would be if a native CSS transition to/from
height:auto was supported. A bit of jQuery simply fills in the element's natural height during the transition.
The exact configuration can be adjusted as needed, but most cases will include the content element to be transitioned and a clickable element, like a button, to trigger the CSS transition.
For example an expanding/collapsing menu:
The open and closed states, including
height values and
transition options are managed entirely in CSS - arguably as they should be - and applied with an
The clickable toggle element and the expanding element can be otherwise styled as desired, but the basic functionality includes the open and closed states and
Each CSS declaration in more detail:
visible- Keeps visually-hidden content also hidden from screen readers and keyboard navigation - an important accessibility feature.
height:0- Sets the initial value - presumably zero, but adjustable as needed.
overflow:hidden- Keeps content hidden during the CSS transition.
transition- Sets the desired animation options - the
heightduration should match.
transition-delay- Removes the
visibilitydelay for the transition from closed to open.
.open class(es) on click:
The HTML, CSS and jQuery so far expands and collapses, but the CSS
height property doesn't natively transition to the
auto value so the transition to and from the
.open state is instantaneous, rather than with the desired animated CSS transition.
A Little Razzle Dazzle
Fortunately, a little jQuery with the
transitionend event and
.scrollHeight property can make up the difference.
Open, close and combined functions form a reusable mini-plugin:
(The function names can be shortened to make this snippet even smaller.)
Updated Click Function
One last step. The snippet to add/remove the
.open class on click can then be updated to use the new
And that's it - one small snippet of jQuery effectively enables CSS transitions to and from
height:auto for any number of use cases.
Here it is in action with a simple expanding/collapsing menu:
Although not an issue for absolutely-positioned elements, animated or not, expanding/collapsing or other potential layout shifts should be used sparingly to avoid the performance impact of content reflow.
Images are often the largest resources on the page, so lazy loading is a simple and valuable strategy to improve loading speed:Lazy Loading Images
Using embedded YouTube videos? Eliminate the impact on initial-load page weight and page speed by loading embedded video on demand:On-Demand Embedded Videos