How can I transition height:0;height:auto; using CSS?
P粉461599845
2023-08-27 11:59:03
<p>I'm trying to use CSS transitions to make <code></code></p><ul> slide down. <p><br /></p>
<p><code></code></p><ul> Starts at <code>height: 0;</code>. On hover, the height is set to <code>height:auto;</code>. However, this results in it just appearing, <em> without </em> transitioning, <p><br /></p>
<p>If I go from <code>height: 40px;</code> to <code>height: auto;</code> then it slides up to <code>height: 0;< ;/code> and then suddenly jump to the correct height. </p>
<p>How else can I do this without using JavaScript? </p>
<p><br /></p>
<pre class="brush:css;toolbar:false;">#child0 {
height: 0;
overflow: hidden;
background-color: #dedede;
-moz-transition: height 1s ease;
-webkit-transition: height 1s ease;
-o-transition: height 1s ease;
transition: height 1s ease;
}
#parent0:hover #child0 {
height: auto;
}
#child40 {
height: 40px;
overflow: hidden;
background-color: #dedede;
-moz-transition: height 1s ease;
-webkit-transition: height 1s ease;
-o-transition: height 1s ease;
transition: height 1s ease;
}
#parent40:hover #child40 {
height: auto;
}
h1 {
font-weight: bold;
}</pre>
<pre class="brush:html;toolbar:false;">The only difference between the two snippets of CSS is one has height: 0, the other height: 40.
<hr>
<div id="parent0">
<h1>Hover me (height: 0)</h1>
<div id="child0">Some content
<br>Some content
<br>Some content
<br>Some content
<br>Some content
<br>Some content
<br>
</div>
</div>
<hr>
<div id="parent40">
<h1>Hover me (height: 40)</h1>
<div id="child40">Some content
<br>Some content
<br>Some content
<br>Some content
<br>Some content
<br>Some content
<br>
</div>
</div></pre>
<p><br /></p></ul></ul>
You should use scaleY.
I made a vendor-prefixed version of the above code on jsfiddle and changed your jsfiddle to use scaleY instead of height.
edit Some people don't like the way
scaleY
converts content. If this is a problem then I'd recommend usingclip
instead.Use
max-height
in transitions instead ofheight
. And set the value ofmax-height
to something larger than your box.See Chris Jordan's answer to here in another JSFiddle demo /stackoverflow.com/a/20226830/18706">