1.3 KiB
1.3 KiB
title, type, tags, cover, dateModified
| title | type | tags | cover | dateModified | |
|---|---|---|---|---|---|
| Height transition | snippet |
|
washed-ashore | 2020-12-30T15:37:37+02:00 |
Transitions an element's height from 0 to auto when its height is unknown.
- Use
transitionto specify that changes tomax-heightshould be transitioned over. - Use
overflow: hiddento prevent the contents of the hidden element from overflowing its container. - Use
max-heightto specify an initial height of0. - Use the
:hoverpseudo-class to change themax-heightto the value of the--max-heightvariable set by JavaScript. - Use
Element.scrollHeightandCSSStyleDeclaration.setProperty()to set the value of--max-heightto 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.
<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');