The simple trick to transition from height 0 to auto with CSS
ฝัง
- เผยแพร่เมื่อ 30 มิ.ย. 2024
- Animating or transitioning to and from height auto is, well, not really possible (though it is being worked on!), but luckily, there is actually a solution using CSS Grid that’s really easy to implement!
🔗 Links
✅ Keith J. Grant’s article on this (also includes a flexbox solution): keithjgrant.com/posts/2023/04...
✅ The first simple example: codepen.io/kevinpowell/pen/po...
✅ The accordion: codepen.io/kevinpowell/pen/NW...
⌚ Timestamps
00:00 - Introduction
00:20 - The setup
01:55 - The transition
02:20 - It works with more content too
02:45 - How I discovered this
03:10 - Using it for an accordion
#css
--
Come hang out with other dev's in my Discord Community
💬 / discord
Keep up to date with everything I'm up to
✉ www.kevinpowell.co/newsletter
Come hang out with me live every Monday on Twitch!
📺 / kevinpowellcss
---
Help support my channel
👨🎓 Get a course: www.kevinpowell.co/courses
👕 Buy a shirt: teespring.com/stores/making-t...
💖 Support me on Patreon: / kevinpowell
---
My editor: VS Code - code.visualstudio.com/
---
I'm on some other places on the internet too!
If you'd like a behind the scenes and previews of what's coming up on my TH-cam channel, make sure to follow me on Instagram and Twitter.
Twitter: / kevinjpowell
Codepen: codepen.io/kevinpowell/
Github: github.com/kevin-powell
---
And whatever you do, don't forget to keep on making your corner of the internet just a little bit more awesome!
This is gold. I spent a while building an accordion in react a couple of weeks ago and had to resort to refs to calculate the height dynamically. Thanks Kevin!
Same! That's just amazing!
Tears in my eyes with glorious smile. It's so relatable
Same 😂
@@demetrx7972 +1
Same😅😅
Make sure to add "grid-row: 1 / span 2;" on the child element. Otherwise the child will animate at a diffrent speed than the parent.
Thank you man, I saw that behavior and I was about to ask about it, this is 10 times better.
This is a critical detail, should be even pinned.
How does this even work? There should be nothing to span since there is only one row...
@@mandokir when transitioning from 0 to 1fr you will get fractional values. The grid system will create a second row to fill up the remaining space to get back to 1fr. So with grid-template-rows: .3fr; you will get a second row that fills the remaining .7fr. It's still weird how the div reacts to the size change because the overall height will shrink to the fraction while it's also divided into the two rows, but... it works
Bless your heart Oxuhs, savior of the day
You have literally fulfilled your tagline goal with me. I may not be great at css yet but I’ve definitely fallen in love with css and front end work.
This is absolutely brilliant!
Having to "kind of" do it with max-height, etc. is always not quite what you want.
Give my secret sauce transition from 0 to auto a try (I haven't seen this trick anywhere):
tab.style.height = 'auto';
const height = tab.offsetHeight;
tab.style.height = 0;
tab.style.height = height + 'px';
And of course a css transition on tab. Don't ask me why but as far as I can tell it does the job perfectly.
@@MrW0rDs You're setting its height to be auto, recording the height it takes up in pixels, then setting its height to 0px, and finally setting its height to the recorded height. Transitions can occur between two pixel values but not auto because sometimes auto is calculated on a subsequent layout refresh. But being that that is the case sometimes your method will fail and capture a height of 0 and your element wont transition at all, or worse if the element has padding the padding will be included in the height you capture and make the element larger than it should, and also your element becomes unresponsive because it has a hard coded pixel value which is very bad for complex UI's and not what auto is supposed to do at all. With the method described in the video none of that is the case, it is a perfect solution. Also if you don't understand how something as simple as that works yet naively use it and suggest others do too, you should take the time to learn the fundamentals and actually understand the code you are writing or you'll make the mistake of using bad code that causes rippling issues through your work you cant even begin to diagnose without the understanding of what its doing.
@@dabbopabblo Thanks for your input! I'm not sure how offsetHeight can ever return a height of 0 since the height is set to 'auto' beforehand, can you elaborate? I made it a simple example but you can see how the transition is suppose to happen from 0 to XXpx, try on a codepen. If responsiveness is a problem you can switch back to auto once the transition is completed, and vice-versa when the tab is toggled. The tab content wrapper must not have a padding, this is not a deal breaker whatsoever. Been using this for 3+ years and haven't seen it fail a single time on any browser, nor has this been reported to me. What I would like to know is why the browser doesn't repaint before the transition happen (probably because 0 => auto => 0 happens so fast, but there must be a technical explanation)
@@MrW0rDs This is how I do it, it's extremely simple.
const contentContainer = < selector here >;
contentContainer.style.maxHeight = isOpen ? `${contentContainer.offsetHeight}px` : '0';
What an awesome little niblet of knowledge. Thank you, Chris, Keith, and, of course, Kevin! Stay awesome.
Omg this is awesome! I had to do an accordion in the job recently and had to use JS to calc the size of elements times their numbers to achieve the same effect. That's why I love this channel!
It's amazing just how happy this made me -- I'm just about done with a project where I had wanted to have this effect on the menu but had given up trying to find a non-horrible solution. Two minutes' work and it's done, looks perfect.
I know that it's likely no-one but me (not even the client) will even notice the difference, but just the knowledge that it's there gives me untold satisfaction.
Thanks Kevin!
Totally forgot about this video and came across it again just now since i was on the lookout for exactly this, since i need it for a project. Amazing as always Kevin!
Kevin, your channel has been _extremely_ helpful to me. This technique is solid gold. Thank you!
Wow - I love this. It saves me lots of code to build a more / less toggle and it's the most straight-forward solution I've seen so far.
The passion everyone can see with you're doing the videos with is priceless, that makes the videos even more valuable!
Hey Kevin, thanks for the shout-out! I’m glad you’re as excited about this as I am 😄
This is absolutely amazing! I was struggling with this issue for a while. This solution is amazingly creative and simple. Thank you
I have searched for this effect for so long but always ended up with some compromised version. It works like charm! Thanks you for sharing.
This is so SO HELPFUL! My collapsible components are now perfect! Had to use some javascript to change overflow to visible once the transition is complete, because I'm using dropdown inside, but the overall result is top notch! Thank you!
I was so happy to see this when you first published it and I just used it again today. As a matter of fact, I made it a collection of helper classes that I can apply to anything and I plan to replace all of my collapsible blocks with this.
Been struggling with this for years, thanks for sharing such an easy solution!
You helped me out a lot, since I had to build accordions at work today. Others have already built accordions in other projects but I really didn't like the implementation since it involved JS and a fixed height. This solution is so smooth, thanks!
Man ! you saved the day!
I remember watching this video as it was released, and today I came back to watch it again because I had the same use case.
Absolute *game changer!!!* Great video Kevin!
Finally it has been done. Congrats on this acheivement!🏆and thanks for sharing.
Thank you so much. I needed that and now my accordion menu works perfectly.
Man I love the way you are so so happy about it. Thanks for the video.😊
Just today I got assigned a task to implement an FAQ where you see the question and, upon clicking on it, the answer gets revealed, with a nice expanding animation. Lucky me, I watched your video before implementing it!
Thank you, Kevin!
OMG! This is the solution i searching for months. Currently i using the max-height trick or i calc the exact height via js. But this is so simple. I Love it!! Thank you Kevin!
Kevin... I was struggling with a clanky animation I have on my project due to layout shifts... this trick has saved the day, there was no better become aware of it than now
Thanks a bunch Kevin! I love your tutorials, always down for some tips and tricks from you.
This is sick! I was having a problem where the font sizes changes with breakpoints throwing away the height i calculated initially, this fixes and I don't have to worry about setting hard height values
This is so cool. And it works! Thank you so much for sharing!
Where was this half a year ago when I needed it for my job!? Thank you for great educational tips and tricks as usual!
I was doing this with the columns the other day for a slide out panel, but for some weird reason I've never thought to go vertical! Thanks for the awesome content Kevin!
Amaizing find, my new vue accordion is ready to rock 💪. Thanks!
Thank you! You are the best! I've been looking for sth like this for about 7 years!🎉🎉🎉
Thanks Kevin! Been looking for something like this for a long time!
I just watched this video 2 days ago. And today, lo and behold... I needed to do exactly this. Fantastic timing! It works like a charm and it definitely would not have occurred to me that this can be done, were it not for this great video! Thank-you!!
This is so good! Thank you Kevin.
Another amazing video! Thank you so much 🙌
this is so cool! why didn't I hear about this sooner? It was a pain for every website I built so far, but not anymore! thanks :)
WOW! This is awesome! I'll use this in a couple projects I've been working on!
This clip was very helpful! Having a dynamic height for a div with that smooth transition is exactly what I was looking for my REACT custom component.
This is awesome, thank you for re-re-sharing!
This is so amazing. Spend many hours to calculate the height of my accordion items dynamically with js after searching for a good css solution. Now after a few lines the magic is done. So great. Thanks a lot!
Genius! Thank you for sharing, fantastic solution! :)
Thank you Kevin! You helped me a lot!
Wow, really great that this is now possible, thanks for sharing!
Short and so sweet… thank you Kevin!
Superb as always. Thank you.
Ive been looking for something like this for a while and omg having such a simple native CSS solution is amazing
This is super useful !! I'll use this on my job, thank you Kevin
Tech job must be great
Hook a brother up 😂
Incredible! Simply simple, but so amazing.
Fantastic, thanks for sharing!
Thank you for sharing this brilliant trick, no more js no more headaches
This is brilliant! Thank you Kevin
This comes at a perfect time, thank you! I will be faced with this problem soon and would have wasted much time for a more or less reasonable solution
You bring joy to the world
Brother this is brilliant! I've spent so much time trying to build a Sidebar with animated width while collapsing...I tried animating font-size to 0 and it worked, but not quite as I wanted, and this solution is exactly what I needed!!!!!!!! Thank you so much!
this is so dope, i just needed it in a project and was referred to this vid by some guy in a stackoverflow question
genuinely thank you!!!
So grateful! ⭐️
this is amazing! nice find :D
I was literally stuck trying to solve the faq accordion challenge by Frontend Mentor with CSS only. It felt almost impossible til this vid notification popped up in front of me!
Thanks man, you came just in the perfect time!
this is a gamechanger.Brilliant. Thanks a lot!
damn i was trying to figure out effective way to create this animation for last 2 weeks and you just made it so easy for me. Thanks Kevin
Brilliant! Thank you
Great trick, thanks for sharing!
It really make my day. Thank you guys
This is a massive game changer. Thank you!
I had this problem today at work and I couldn't get it to work properly. Checking youtube, this video comes up and fixes my problem! Thanks alot!
Wow! I was trying to do this with the width of a sidebar just a couple days ago and gave up. Now I know how to do it! Thanks!
Cool! ❤ I always had to create a complicated component for such things
This is a great tip. Thanks man ❤️
This is awesome!! I can finally stop using JS to define innerHeight at div's style!!! Thanks so so much!
Kevin you are my favorite mentor. Stay blessed 💜
Awesome! Thanks, buddy.
This was really helpful , I have used this trick in my projects and it's really convenient
Thats exactly what i wanted. I was struggling with the height auto issue in React, because auto won't trigger any css animation, making everything so awkward. Now you saved my life.
This kinda stuff gets me up in the morning. Awesome Kevin, thanks for sharing! Accordion-ception incoming.
That's great!!! Love it!
It is super useful because I got it when I really need it. I'm gonna it to my client’s project now. Cheers!
Thank you for sharing this. You're awesome
thanks kevin really helped me alot
You are a brilliant man, thank you so much.
You always surprise me with your tips and tricks.
Amazing, thanks a lot!
🎉 Wow, it took 10 years to come up with a css only solution. I remember using the max-height hack for accordions in 2013… this is amazing.
This is crazy! I've been struggling today with exact this requirement. Ending up with transitioning the min-height from 0 to e.g. 400px and setting the height from 0 to auto. I've also added the scaleY() transform, which actually looks very awesome. But from my point of view, this is a much cleaner solution than setting the min-height to a random value. Thanks for sharing this cool trick.
Great discovery! Thanks Kevin.
Helped a lot..Thanks❤❤✌🏻✌🏻
I figured this out once, and forgot what I did. Thank you so much for reminding me!!!! You are awesome. This is awesome :)
Awesome, awesome, awesome. Thank you Kevin
Really clever way of doing it, thanks.
This is gold. Thanks!
Thanks Kevin, you are a top: G; and a life saver.
I have been using the min-height hack for a while which was ok but was problematic since when you put a higher min-height it takes long time for the transition to complete, but this is just amazing, you are a wizard 🧙♂
This is great, now I don't need to use extra unnecessary javascript to animate these transitions anymore, thanks to people like you that make this so much simpler
You wouldn't have needed to use JS to perform the animation/transition though. The minimum implementation before this was to find the height value and set it, but to use transition: height ...;
Thanks man, you are the best!
This is unbelievable!!!! Thank you so much!
My mind is blown.... it's be JS 100% to achieve this for so many years...
Big thanks to Keith and you, Kevin))🙂
Broe I had be struggling for so long with this that I endedup using JS everything time I need an accordion.This is very cool.
I have came back to say a big thank you. I watched this video the very day it was uploaded and this is the 7th day. I'm so excited for this hack, it's actually an eye opener. I stopped struggling with drop-down after watching this... I'm currently working on a project and this hack really helped me. I implemented this trick on my project and it works just very cool, no stress 😊. Thanks allot for such a helpful and quality content. Your smiles and expression as whole while teaching gives confidence 💚
amazing stuff! Thanks!!!!
This is great. Will use it for sure!