transition: all 仅对可动画的CSS属性生效,如color、opacity、transform等,但display、z-index等不可插值属性无效;显式声明关键属性更安全可控。
transition: all 并不是真的“所有 CSS 属性”都会被过渡,它只对**可动画的属性**生效。比如 display、z-index、content 这类不可插值的属性,即使写了 all 也不会产生过渡效果。浏览器内部有一份可过渡属性白名单,像 color、opacity、transform、width、height、background-color 等都支持;但 font-size 虽然可过渡,却可能因字体加载或 subpixel 渲染导致视觉跳变。
看似方便,实际容易引发意外动画:
transition: all 0.3s 会让所有后续样式变更(包括 JS 动态加 class、伪元素内容变化、甚至 outline 或 box-shadow 的微小改动)全都带上过渡,调试时难以定位源头height: 0 → auto 无法过渡,必须配合 max-height 或 transform: scaleY()
all 可能触发不必要的重排(reflow),尤其涉及 width/height 时,造成卡顿will-change: transform,而子元素用 all 过渡 left 和 top,可能因层叠上下文冲突导致动画撕
裂比起 all,显式声明要过渡的属性更安全、意图更清晰,也利于性能优化:
button {
background-color: #ccc;
color: #333;
transform: scale(1);
transition: background-color 0.2s, color 0.2s, transform 0.2s ease-out;
}
button:hover {
background-color: #007bff;
color: white;
transform: scale(1.05);
}
这样写的好处:
border-color 在 hover 里没改,就不会参与过渡)transform 用 ease-out,opacity 用 linear
真有场景需覆盖多数视觉变化(比如组件主题切换、暗色模式切换),不建议依赖 all,而是:
--bg-primary、--text-emphasis,再对这些变量做 transition
transform + opacity 组合,避开重排getComputedStyle(el).getPropertyValue('--my-var') 配合 JS 控制过渡时机,比纯 CSS all 更可靠真正难的不是让所有东西动起来,而是让该动的动得准、不该动的不动——all 看似省事,反而掩盖了哪些变化值得被用户感知。