因为height: auto无法参与动画,浏览器需明确数值进行过渡。推荐使用max-height或JS获取scrollHeight实现流畅折叠展开效果。

在CSS中实现元素的折叠与展开动画,直接使用 animation 控制 height 看似简单,但实际操作中容易遇到问题。因为 height: auto 无法参与CSS动画过渡(transition 或 animation),导致无法平滑展开或收起内容。
CSS 动画需要明确的数值起点和终点。当高度从 0 到 auto 时,auto 是一个动态计算值,浏览器无法知道目标高度是多少,因此不能生成中间帧。
一种常见解决方案是用 max-height 替代 height:
max-height: 0、overflow: hidden
max-height(如 500px)transition 实现平滑动画立即学习“前端免费学习笔记(深入)”;
.collapsible {
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease;
}
<p>.collapsible.expanded {
max-height: 500px; /<em> 要大于内容实际高度 </em>/
}</p>这种方法简单有效,但缺点是如果 max-height 设置过大,动画时间会变长,即使内容很短。
更精确的做法是结合 JavaScript 动态设置目标高度:
position: absolute; visibility: hidden)scrollHeight
height 并触发动画立即学习“前端免费学习笔记(深入)”;
const content = document.querySelector('.content');
const height = content.scrollHeight + 'px';
<p>// 展开
content.style.height = height;</p><p>// 折叠
content.style.height = '0';</p>CSS 配合:
.content {
height: 0;
overflow: hidden;
transition: height 0.3s ease;
}
若使用 @keyframes 实现 height 动画,仍需具体数值。例如:
@keyframes slideDown {
from { height: 0; }
to { height: 200px; } /* 必须是固定值 */
}
这意味着它只适用于已知高度的内容,通用性差。
基本上就这些。想要流畅的折叠展开效果,推荐使用 max-height 方案快速实现,或结合 JS 动态读取高度实现更精准控制。关键点是理解 auto 无法动画,必须转换为具体数值。
以上就是在css中animation与height折叠展开的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号