I was struggling trying to animate the width of a <div>
from a fixed px width to a 100% (or auto) width. The idea was to have a completely fluid 2 columns layout. A main col taking all the space and a right col with a fixed width. Then, on a particular user action, the right col animates until taking all the remaining space (overlapping the main col). I needed to achieve the effect only with css transitions.
Here’s how I did it…
.right-col { min-width:200px; /* min-width as the pixel value */ width:0%; /* width as the % value */ transition:width .8s ease; /* css transition applied to width */ } .expanded { width:100% !important; }
Instead of trying to animate from 200px to 100% (which is impossible), I transitioned on the width from 0% to 100% (which works) and I use min-width to override the initial width:0% 🙂 Just put the .expanded class on the .right-col <div>, it will work like a charm.
But be careful min-width is stronger than width. So when you’ll apply the new width (in %) min-width will still override it, you have several options to handle this:
* increase the .expanded specificity (eg: .right-col.expanded or maybe: div.expanded)
* or use the !important
rule, usually it’s a bad solution but here it does the trick perfectly.
Here’s a jsfiddle of a working exemple. It works in all browsers, except of course in IE where transitions are not supported, but as it gracefully degrades, we can say it works every where 🙂
A note about hardware accelerated transitions
Remember basically all css transitions are not hardware accelerated and thus have flickering problems on mobile plateforms (iOS + Android) when applied on “big” elements. By “big” I mean almost anything else than a simple single div 🙁 you’ll need translate3d(x,y,z) if you want hardware accelerated transitions (means it triggers the GPU instead of the CPU) … (means transitions are very very smooth, even on mobiles and even on “big” elements). But translate3d will help only if you need to move an element on the page, here we try to animate the dimensions of a <div> element. So, sadly, no GPU in this case.
I’m confused… why min-width is needed instead of width. Did I lost sth ?
I modified your jsfiddle exemple with width and it also works well (hover on the .right-col)
http://jsfiddle.net/judNR/118/
Indeed! Transitioning from px to % is now supported in both Chrome and Firefox 🙂
Hi there. Yes, it won’t work this way. At least not for every browser.
What you need to use is max-width. Initially set it equal to height, and then change it to value, which is for sure greater than any possible width value.
Here is an article on stackoverflow: http://stackoverflow.com/questions/3508605/how-can-i-transition-height-0-to-height-auto-using-css