I use CSS transitions a lot. Today I came across a problem that I’ve managed to avoid for a while: animating the height of elements to auto
.
Let’s say we want to change the height of an element when hovering over it (or over a containing element). If we define a specific height for the element for each state, we can easily use CSS transitions like in this example.
But we don’t always know how high the element is when it’s hovered over, especially when it contains an unknown amount text. And if the height of an element at the end of the transition is set to auto
, it doesn’t work.
There is a workaround for this, but it’s a bit hacky admittedly: instead of using height
as transition-property
we can use max-height
to (almost) accomplish what we want. We just have to set it to an unlikely high value and it will work as expected, like in this example. There’s a downside to this: if you set max-height
too high, the transition will take longer.
That’s what I learnt today.