I'm trying to animate an element's height from a preset one to the one that's dependent on what's inside (what height: auto
would set). Because an animation doesn't work for height: auto
(going to or from) I thought a solution could be to save the current height, set height: auto
on an element to get the final height and save that, then reset the element's height to initial and then set it to the final height. The "blink to auto" the user wouldn't notice and the last change should result in an animation.
const containerBlockDiv = document.querySelector('.container-block')
const childBlockDiv = document.querySelector('.child-block')
const containerCurrentHeight = containerBlockDiv.scrollHeight
containerBlockDiv.style.height = 'auto'
const containerNewHeight = containerBlockDiv.scrollHeight
containerBlockDiv.style.height = `${containerCurrentHeight}px`
containerBlockDiv.style.height = `${containerNewHeight}px`
.container-block {
display: inline-block;
background-color: red;
height: 50px;
width: 20px;
transition: height 1s;
}
.child-block {
display: inline-block;
height: 100px;
}
<div class="container-block">
<div class="child-block"></div>
</div>
Why doesn't this work?