CSS transition from a fixed px width to an auto width

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.

Be Sociable, Share!

    Commentaires

    Leave a Reply to jkneb Cancel reply

    Your email address will not be published. Required fields are marked *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>