I also faced this problem writing my accordion library (github.com/oncode/handorgel). I solved it by using an inner div and animating the height of its parent element from zero to the offsetHeight of the inner div every time it is opened.
I’m a professional software writer specialized in Web technologies and engaged in indie application development. I consider myself to be a man of faith. I pursue honesty, integrity, and compassion.
Does this still work if the parent element has display: none? It's good to hide the content from screen readers when it's collapsed (I'm assuming most screen readers skip content that's display: none).
Sorry for the subpar formatting. I'm writing from my phone.
Doesn't work if the parent element has display: none. Also the animation won't work.
But when you remove "display: none" prior to opening and after closing (when transition has finished), you can add "display: none" and everything will work. I set display: none like this in my library to avoid screen readers reading the content and preventing that elements can be focused (e.g. when tab is used).
I’m a professional software writer specialized in Web technologies and engaged in indie application development. I consider myself to be a man of faith. I pursue honesty, integrity, and compassion.
Right, so you can't use getBoundingClientRect to get the size of the child container when the parent has display: none?. So you have to first remove display:none, then measure, then animate?
I also faced this problem writing my accordion library (github.com/oncode/handorgel). I solved it by using an inner div and animating the height of its parent element from zero to the offsetHeight of the inner div every time it is opened.
Does this still work if the parent element has display: none? It's good to hide the content from screen readers when it's collapsed (I'm assuming most screen readers skip content that's display: none).
Sorry for the subpar formatting. I'm writing from my phone.
Doesn't work if the parent element has display: none. Also the animation won't work.
But when you remove "display: none" prior to opening and after closing (when transition has finished), you can add "display: none" and everything will work. I set display: none like this in my library to avoid screen readers reading the content and preventing that elements can be focused (e.g. when tab is used).
Right, so you can't use
getBoundingClientRect
to get the size of the child container when the parent hasdisplay: none
?. So you have to first removedisplay:none
, then measure, then animate?Exactly, all
getBoundingClientRect
properties would be 0 when the parent hasdisplay: none
.That's a great idea! Would that mean that you can add content to the inner div while the outer div is collapsed?
Exactly, you can add the content while it's collapsed and it will open to the correct height.
that's fantastic. I'm gonna try that out! Thanks!