3.0 KiB
3.0 KiB
Height transition
Transitions an element's height from 0 to auto when its height is unknown.
HTML
<div class="trigger">
Hover me to see a height transition.
<div class="el">content</div>
</div>
CSS
.el {
transition: max-height 0.5s;
overflow: hidden;
max-height: 0;
}
.trigger:hover > .el {
max-height: var(--max-height);
}
JavaScript
var el = document.querySelector('.el')
var height = el.scrollHeight
el.style.setProperty('--max-height', height + 'px')
Demo
Hover me to see a height transition.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque congue placerat nunc a volutpat. Etiam placerat libero porttitor purus facilisis vehicula. Mauris risus mauris, varius ac consequat eget, iaculis non enim. Proin ut nunc ac massa iaculis sodales id mattis enim. Cras non diam ac quam pharetra fermentum vel ac nulla. Suspendisse ligula urna, porta non lobortis non, lobortis vel velit. Fusce lectus justo, aliquet eu fringilla auctor, sodales eu orci. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
Explanation
CSS
transition: max-height: 0.5s cubic-bezier(...)specifies that changes tomax-heightshould be transitioned over 0.5 seconds, using anease-out-quinttiming function.overflow: hiddenprevents the contents of the hidden element from overflowing its container.max-height: 0specifies that the element has no height initially..target:hover > .elspecifies that when the parent is hovered over, target a child.elwithin it and use the--max-heightvariable which was defined by JavaScript.
JavaScript
el.scrollHeightis the height of the element including overflow, which will change dynamically based on the content of the element.el.style.setProperty(...)sets the--max-heightCSS variable which is used to specify themax-heightof the element the target is hovered over, allowing it to transition smoothly from 0 to auto.
Browser Support
Requires JavaScript
⚠️ 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.