How to transition to auto in CSS

2017-01-23 | #css, #solution, #webdev

I stumble upon this nonsense, every fricking time I want to use CSS transitions on anything even slightly dynamic:

With CSS transitions you can nicely transition between two set values, but the whole thing falls apart as soon as one of the dimensions you want to animate has a non-specific value like "auto".

Why this is, is beyond me. Of course the browser engine knows the exact dimensions of something being dynamically sized by its content. Well, whatever ...

But there is a little CSS hack you can use, to achieve a dynamic transition, with the little caveat, that you are forced to define the max-value of the dimension you want to animate, but that should be manageable in most cases.

Lets say you want to have a button, which sports an icon in its non-hover state and, on hover, reveals its text of unknown length. Have a look at this Stylus snippet


min-width 50px

height 50px


content '+'

display block

float left

width 50px

text-align center

line-height 50px


display block

float left

user-select none

pointer-events none

overflow hidden

max-width 0

color transparent

transition max-width 200ms, padding-left 200ms, padding-right 200ms, color 200ms



max-width 500px

color white

transition max-width 200ms, padding-left 200ms, padding-right 200ms, color 200ms

The trick here is to animate "max-width" instead of width and setting explicit values on both ends. Interesting enough, in this case you'll also have to set the transition on both ends. Because ... reasons.

A little problem with this approach is, that the browser indeed transitions the whole width between both max values, but of course only shows change relevant to your element, so you should keep the max value in close vicinity to a realistic max value. Also keep in mind that the "felt" animation offset now changes a little based on the elements contents, since the transition, while always being the same, now effects more or less of the element's contents, depending on the amount the contents fill up the max value.

There, all set to go, animate away m'lord!