小能豆

How can I transition height: 0; to height: auto; using CSS?

javascript

I am trying to make a <ul> slide down using CSS transitions.

The <ul> starts off at height: 0;. On hover, the height is set to height:auto;. However, this is causing it to simply appear, not transition,

If I do it from height: 40px; to height: auto;, then it will slide up to height: 0;, and then suddenly jump to the correct height.

How else could I do this without using JavaScript?

#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;
}
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>

阅读 200

收藏
2023-12-26

共1个答案

小能豆

Unfortunately, you can’t directly use height: auto in a CSS transition to create a smooth animation because auto doesn’t represent a numeric value that can be animated.

However, you can achieve a similar effect using a combination of max-height and a specific value. Here’s an example:

#parent {
  overflow: hidden;
}

#child {
  max-height: 0;
  overflow: hidden;
  background-color: #dedede;
  transition: max-height 1s ease;
}

#parent:hover #child {
  max-height: 200px; /* Adjust the value based on your content */
}

h1 {
  font-weight: bold;
}

In this example, max-height is used instead of height. The max-height is set to 0 by default, and on hover, it is set to a value that is large enough to accommodate your content.

Here’s the modified HTML:

<div id="parent">
  <h1>Hover me</h1>
  <div id="child">
    Some content<br>
    Some content<br>
    Some content<br>
    Some content<br>
    Some content<br>
    Some content<br>
  </div>
</div>

This way, you get a smooth transition when hovering over the parent, and the content slides down without abruptly jumping to a height of auto. Adjust the max-height value to suit your actual content.

2023-12-26