Last Updated: September 09, 2019
·
2.539K
· stffndtz

CSS3 transition to 'auto'-value

Yesterday i ran into a common issue: transitioning to an individual height with the value 'auto'.

Problem is, as soon as you have an element like

.transition-box {
  height: 0;
  -webkit-transition: 500ms;
  -moz-transition: 500ms;
  -ms-transition: 500ms;
  -o-transition: 500ms;
  transition: 500ms;
  overflow: hidden;
}

and want to have a transition to

.transition-box:hover {
  height: auto;
}

there won't be any animation, it just 'jumps' open.

To avoid that, simply use max-height and set it to a value bigger than your box will ever be.
Look at the example, implying '.transition-box' will never be bigger than 999px:

.transition-box {
  max-height: 0;
  -webkit-transition: 500ms;
  -moz-transition: 500ms;
  -ms-transition: 500ms;
  -o-transition: 500ms;
  transition: 500ms;
  overflow: hidden;
}

.transition-box:hover {
  max-height: 999px;
}

It's Magic!

Also works like a charm for max-width.

BE CAREFUL

Don't take it to far - The transition in the above example will animate all the way to 999px - so it looks like the transition is really fast. Try setting transition-duration to something that makes it look accurate.