【CSS】优雅解决动态高度的动画问题

2026-03-24 14:01:22

点击下面这个按钮,可以看到有个动画效果。

静夜思
李白
窗前明月光
疑是地上霜
举头望明月
低头思故乡

看下源码,下拉框的高度是一个固定值 (height:170px;),使用 transition 做动画非常的简单。

<style>
    .box {
        height: 0px;
        width: 200px;
        overflow: hidden;
        background-color: aquamarine;
        transition: height 0.5s;
    }

    .box.open {
        height: 170px;
        transition: height 0.5s;
    }
</style>
<button onclick="document.querySelector('.box').classList.toggle('open')">
    点击切换动画效果(固定高度 height: 170px;)
</button>
<div class="box">
    <div>静夜思</div>
    <div>李白</div>
    <div>窗前明月光</div>
    <div>疑是地上霜</div>
    <div>举头望明月</div>
    <div>低头思故乡</div>
</div>

有的业务场景下拉高度是不固定的,比如 Antd-树形结构表格
将 height 修改为 auto,会发现动画效果失效了。子项会突然出现,突然消失。

.box.open {
    height: auto;
    transition: height 0.5s;
}
静夜思
李白
窗前明月光
疑是地上霜
举头望明月
低头思故乡

在这之前,如果希望动态高度的下拉框具有动画效果,需要去计算下拉框的真实高度,非常的麻烦。

自从 Chrome 129+ 之后,新增 CSS 属性优雅解决动态高度的动画问题。

第一个方法是在 :root 伪类选择器中添加 interpolate-size: allow-keywords;,即可全局启用对 auto、min-content、max-content、fit-content 等关键词的过渡支持。

:root {
  interpolate-size: allow-keywords; /* 启用关键词插值 */
}

.box.open {
    height: auto;
    transition: height 0.5s;
}

第二个方法是使用 css 新增函数 calc-size() 实现。

.box.open {
    height: calc-size(auto, size);
    transition: height 0.5s;
}
静夜思
李白
窗前明月光
疑是地上霜
举头望明月
低头思故乡

calc-size() 这个函数非常灵活,当你需要对内在尺寸进行数学运算时,calc-size() 比 interpolate-size 更强大。
比如在上面那个例子基础上,希望下拉框实际高度 = 内容高度(auto) + 50px,参考如下代码编写:

.box.open {
    height: calc-size(auto, size + 50px);
    transition: height 0.5s;
}
静夜思
李白
窗前明月光
疑是地上霜
举头望明月
低头思故乡

返回首页

本文总阅读量  次
皖ICP备17026209号-3
总访问量: 
总访客量: