Hi, I need some help in CSS. I’ve a div , I want to add transition to this div such that each time it’s height changes , It should change smoothly . I added transition: 2s height; to my div . And When I change the height of div it’s not changing smoothly .
You can’t do this with auto height, which (I know) is a bit annoying if you want to code your own accordion where the height of the elements is different for each, and also changes with viewport size.
Here’s a (very long) thread on Stack Overflow about this problem, with various solution of various quality.
To sum up a few:
use jQuery library and its .slideUp and .slideDown methods
(importing a whole library only for one effect feels a little over-kill though)
instead of height, animate max-height:
.acc__content {
max-height: 0;
overflow: hidden;
padding-left : 0.5rem;
transition: 2s ease-in-out max-height;
}
.open {
max-height: 200px; /* this needs to be higher than the height it could possibly have */
}
The downside is that the speed of the animation will now vary for elements of different sizes. The more the actual height differs from the value you’ve specified in the .open class, the faster the animation will become.
JS (use the scrollHeight property to read the actual height of the element):
for (let i = 0; i < headingEle.length; i++) {
headingEle[i].addEventListener('click', function (e) {
let clickedEle = e.target;
let content = clickedEle.nextElementSibling;
// use the class only to determine whether the content is currently open
if (content.classList.contains('open')){
content.classList.remove('open')
content.style.height = 0;
} else {
content.classList.add('open')
content.style.height = content.scrollHeight + 'px';
}
});
}
The last method using JS would be the best in my opinion for this use case, but you can experiment with all of them to see what works best for you.