The CSS transition
property does not work with height: auto
. Therefore, to work around this limitation, you can do any of the following:
Setting a Fixed height
Value
You can set a fixed height
value using CSS, which allows the browser to easily calculate intermediate values during the transition, making the transition animation look smooth.
For example, let's suppose you have the following HTML elements:
<div id="parent"> <div id="child">Foo</div> </div>
To set the height
of the child <div>
to 200px
in your CSS, you can do the following:
#child { height: 0; transition: height 0.5s ease; background: blue; } #parent:hover > #child { height: 200px; }
Using this approach has the following pros and cons:
- It's easy to implement;
- It works well for elements with a known fixed height;
- It does not work well for elements with dynamic content or height;
- It might require manual adjustment if the height of the element changes.
Using the max-height
Property
You could use the max-height
property instead of height
, setting it to a number larger than the maximum height the element will ever need to be.
For example, let's suppose you have the following HTML elements:
<div id="parent"> <div id="child">Foo</div> </div>
If the height
of the child <div>
is going to be a maximum 200px
, then you can do the following:
#child { max-height: 0; transition: max-height 0.5s ease; background: blue; } #parent:hover > #child { max-height: 200px; }
Using this approach has the following pros and cons:
- It's easy to implement;
- It works well for elements with dynamic content or height;
- It may cause issues with nested elements or content that exceeds the
max-height
; - It can be impacted by changes to font size, line height, or padding.
Using transform: scaleY()
You can use transform: scaleY()
to achieve the desired animation effect without the need for fixed height values.
For example, let's suppose you have the following HTML elements:
<div id="parent"> <div id="child">Foo</div> </div>
To transition the height of the element using the transform: scaleY()
style rule, you can do the following:
#child { transform: scaleY(0); transform-origin: top; transition: transform 0.5s ease; background: blue; } #parent:hover > #child { transform: scaleY(1); }
Using this approach has the following pros and cons:
- It can be used for elements with dynamic content or height;
- It does not cause issues with nested elements or content;
- It may cause distortion of nested elements or content;
- It may cause performance issues with larger elements.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.