如何通过CSS将高度从0过渡到auto?

发布时间 2023-11-01 19:56:54作者: 小满独家

内容来自 DOC https://q.houxu6.top/?s=如何通过CSS将高度从0过渡到auto?

你可以尝试使用max-height属性来实现这个效果,而不是使用height属性。这样,在悬停时,<ul>的高度会逐渐增加,而不会出现突然跳跃的情况。以下是修改后的CSS代码:

#child0 {
  max-height: 0;
  overflow: hidden;
  background-color: #dedede;
  -moz-transition: max-height 1s ease;
  -webkit-transition: max-height 1s ease;
  -o-transition: max-height 1s ease;
  transition: max-height 1s ease;
}
#parent0:hover #child0 {
  max-height: auto;
}
#child40 {
  max-height: 40px;
  overflow: hidden;
  background-color: #dedede;
  -moz-transition: max-height 1s ease;
  -webkit-transition: max-height 1s ease;
  -o-transition: max-height 1s ease;
  transition: max-height 1s ease;
}
#parent40:hover #child40 {
  max-height: auto;
}
h1 {
  font-weight: bold;
}

这样,当你悬停在两个不同的<div>元素上时,它们的高度将以平滑的方式过渡,而不是突然跳跃。


在过渡中使用max-height而不是height,并设置一个比框体实际高度更大的值。

Chris Jordan在一个答案中提供了一个JSFiddle演示,请参阅:http://jsfiddle.net/thechrisjordan/3Fc7D/23/

#menu #list {
    max-height: 0;
    transition: max-height 0.15s ease-out;
    overflow: hidden;
    background: #d5d5d5;
}

#menu:hover #list {
    max-height: 500px;
    transition: max-height 0.25s ease-in;
}
<div id="menu">
    <a>悬停我</a>
    <ul id="list">
        <!-- 创建一个或多个列表项,以查看动画效果 -->
        <li>项目</li>
        <li>项目</li>
        <li>项目</li>
        <li>项目</li>
        <li>项目</li>
    </ul>
</div>