Animation + CSS = M A Z I C !

Animation + CSS = M A Z I C !

A walkthrough of how you can apply CSS transition animation for variable height.

Hi everyone,

Recently I worked on CSS transition animations as part of one use-case for my side project. The scenario was like this – I have to animate a ‘div’ to a certain height when I hover on it. So, I had followed the general straightforward way of giving a transition-duration CSS rule for the height property of that div It looks like –

div {
    height : 0;
}

div:hover div {
    height:50px;
    transition: height 2s;
}

In the above CSS code, by default, the height of the div will be 0, so it will not be visible, and if we hover on the button, the height will become 50px and it will increase from 0 to 50px in 2 seconds as we have given transition CSS shorthand rule for it.

Everything worked fine till then. But the caveat here I faced was that the div is not always of the same height. Sometimes the inner-content will require 100px and sometimes 300px. Basically, it will vary between 50px to 500px.

In that case, the height of the div should be kept as fit-content so that, the height will automatically vary based on the inner content (which is variable).

div {
    height : 0;
}
button:hover div {
    height: fit-content;
    transition: height 2s;
}

Now, the real problem has raised, the animation will not work if we keep the height as fit-content. The transition-delay of 2 seconds will not affect the div, as a result, when I hover on it, it will suddenly increase its height instead of the 2 seconds delay.

Here I have two possible ways that I can take, one is to use fixed height instead of fit-content and the second is to google for the solution. As I knew that the content of the ‘div’ cannot be fixed, I had to choose the second one and started finding out solutions in internet forums like StackOverflow. Finally, after a long session of googling, I found a solution that says that I can animate max-height instead of animating height. This max-height CSS property represents the max-height of a ‘div’. So, whatever height is lesser than the specified max-height is visible. As I already analyzed before that, the height of the ‘div’ will vary anywhere between 50px to 500px, my max-height was 500px. So, I had modified the above CSS code like this –

div {
    max-height : 0;
}
div:hover div {
    max-height: 500px;
    transition: max-height 2s;
}

Everything was perfect and worked fine.

This was the challenge that I faced recently and how I overcome it by finding a solution.

Hope you found it useful.

Did you find this article valuable?

Support Devalla Sai Charan by becoming a sponsor. Any amount is appreciated!