Is it possible to create a smooth height transition for an element when the target height is unknown?
Replacing height: unset
with height: 100px
allows the animation to work, but this presents a problem as the height needs to be based on content and may vary for different elements.
Similarly, using max-height
rather than height
requires a hardcoded value (e.g. 1000px
) which means that for a shorter item, there may be a delay before the animation begins.
$('.c').change(function() {
for(var i = 1; i <= 3; i++) {
var item = $('#item' + i)
if($('#c' + i).prop('checked')) item.addClass('show')
else item.removeClass('show')
}
})
.item {
border: 1px solid red;
position: relative;
overflow: hidden;
height: 0;
transition: all 1s;
}
.item.show {
height: unset;
transition: all 1s;
}
<div>
<input type="checkbox" class="c" id="c1" checked />
<input type="checkbox" class="c" id="c2" />
<input type="checkbox" class="c" id="c3" checked />
</div>
<div class="items">
<div id="item1" class="item show">
<h3>Lorem ipsum</h3>
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
<div id="item2" class="item">
<h3>Lorem ipsum</h3>
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
</div>
<div id="item3" class="item show">
<h3>Lorem ipsum</h3>
Lorem ipsum dolor sit amet.
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>