Height transition

Sang
Written by Sang on
Height transition

Transitions an element’s height from 0 to auto when its height is unknown.

<div class="trigger">
	Hover me to see a height transition.
	<div class="el">content</div>
</div>
.el {
	transition: max-height 0.5s;
	overflow: hidden;
	max-height: 0;
}

.trigger:hover > .el {
	max-height: var(--max-height);
}
const el = document.querySelector('.el');
const height = el.scrollHeight;

el.style.setProperty('--max-height', height + 'px');
Demo

See the pen on CodePen.

Explanation

el.scrollHeight is the height of the element including overflow, which will change dynamically based on the content of the element.

el.style.setProperty(...) sets the --max-height CSS variable which is used to specify the max-height of the element the target is hovered over, allowing it to transition smoothly from 0 to auto.

Browser Support

source: 30 seconds of knowledge