Transitions an element's height from 0
to auto
when its height is unknown.
- Use
transition
to specify that changes tomax-height
should be transitioned over. - Use
overflow: hidden
to prevent the contents of the hidden element from overflowing its container. - Use
max-height
to specify an initial height of0
. - Use the
:hover
pseudo-class to change themax-height
to the value of the--max-height
variable set by JavaScript. - Use
Element.scrollHeight
andCSSStyleDeclaration.setProperty()
to set the value of--max-height
to the current height of the element. - Note: Causes reflow on each animation frame, which will be laggy if there are a large number of elements beneath the element that is transitioning in height.
Preview
Hover me to see a height transition.
Additional content
<div class="trigger"> Hover me to see a height transition. <div class="el">Additional content</div> </div>
.el { transition: max-height 0.3s; overflow: hidden; max-height: 0; } .trigger:hover > .el { max-height: var(--max-height); }
let el = document.querySelector('.el'); let height = el.scrollHeight; el.style.setProperty('--max-height', height + 'px');
Recommended snippets
Tip: The perfect duration for CSS transitions
CSS, Article
Learn how to make your CSS transitions feel perfect when users interact with elements on the page with this simple tip.
Staggered animation
CSS, Animation
Creates a staggered animation for the elements of a list.
Tip: CSS easing variables
CSS, Article
Learn how to use the
cubic-bezier()
class of easing functions and create beautiful animations that stand out.