display 无法过渡因属离散属性,浏览器不能插值;应改用 opacity、transform、max-height 等可动画属性,并在初始类中声明 transition 才能生效。

transition 为什么对 display 无效
直接给 display: none 加 transition 不会生效,因为 display 是离散属性,浏览器无法插值计算 none 到 block 的中间状态。想实现列表项的平滑显隐或位移,得避开 display,改用可动画的属性,比如 opacity、transform、max-height。
用 opacity + transform 实现颜色和位置过渡
这是最可靠的方式:颜色变化靠 color 或 background-color,位置变化靠 transform: translateY()(避免触发重排,性能好)。必须同时在「默认态」和「目标态」都声明 transition,否则只有一半有动画。
示例:
li {
opacity: 1;
transform: translateY(0);
color: #333;
transition: opacity 0.2s ease, transform 0.2s ease, color 0.2s ease;
}
li.hidden {
opacity: 0;
transform: translateY(-10px);
color: #999;
}
注意点:
立即学习“前端免费学习笔记(深入)”;
-
transition要写在初始类(如li)上,不是只写在.hidden里 - 多个属性过渡要显式列出,或用
all 0.2s ease(但慎用,可能意外动到不该动的属性) -
transform比top/margin更高效,后者会触发 layout
max-height 过渡适合展开/收起场景
当列表项需要「高度变化」(比如点击展开详情),max-height 是常用折中方案——因为 height: auto 无法过渡,但设一个足够大的 max-height 值(如 500px),再配合 overflow: hidden,就能模拟出高度动画效果。
关键细节:
- 起始态设
max-height: 0,结束态设max-height: 500px(需大于内容实际高度) - 必须加
overflow: hidden,否则内容会溢出 - 过渡时间别太长,
max-height动画本质是线性拉伸,过长会显得拖沓 - 如果内容高度差异大,500px 可能不够或冗余;更健壮的做法是用 JS 测高 +
height过渡,但复杂度上升
伪类状态(如 :hover)的 transition 写法
列表项悬停变色+上浮,是最常见的交互。这里容易漏掉的是「反向过渡」——只写 li:hover { transform: translateY(-2px); },鼠标移出会突兀跳回,必须确保基础样式已有 transition 声明。
正确写法:
li {
transition: transform 0.15s cubic-bezier(0.2, 0.8, 0.4, 1), color 0.15s ease;
}
li:hover {
transform: translateY(-2px);
color: #007bff;
}
补充说明:
- 用
cubic-bezier()替代ease可让上浮更自然(先慢后快再慢) - 不要对
:active单独加 transition,它依赖于基础态的声明 - 移动端要考虑
:focus和:focus-visible,避免键盘用户无反馈
display、height: auto)或漏写了基础过渡声明。










