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

.button

min-width 50px

height 50px

&:before

content '+'

display block

float left

width 50px

text-align center

line-height 50px

.caption

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

&:hover

.caption

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.

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