CSS过渡必须写在默认状态而非:hover中,因为transition需初始存在才能监听属性变化;若仅在:hover中定义,移入时已发生突变、移出时无过渡规则,导致动画失效。

CSS过渡(transition)必须写在元素的默认(非:hover)状态上,而不是只写在 :hover 伪类里,否则动画不会生效。
为什么写在 hover 里无效?
因为 transition 的作用是定义“属性变化时如何过渡”,它需要在**初始状态就存在**,才能监听后续的变化。如果只在 :hover 中声明,那么鼠标移入时才添加过渡规则,浏览器已开始执行属性变更(比如颜色突变),来不及触发过渡效果;移出时又因默认状态没写 transition,导致回退也是瞬时的。
正确写法:过渡写在默认状态
把 transition 放在元素的基础选择器中,确保进出都有过渡:
.btn {
background-color: #007bff;
color: white;
transition: background-color 0.3s ease, color 0.3s ease; /* ✅ 写在这里 */
}
.btn:hover {
background-color: #0056b3;
color: #f8f9fa;
}常见遗漏点
-
漏写可过渡的属性名:如只写
transition: 0.3s,不指定属性,默认不生效(部分浏览器可能有兼容行为,但不可靠) -
初始值和 hover 值不可过渡:比如从
display: none切到block,或涉及height: auto,这些本身不支持过渡,需换用opacity、max-height或transform等可动画属性 -
过渡时间太短或为 0:检查是否误写成
transition: all 0s或单位缺失(如写成300而非0.3s)
进阶建议:用 transform 替代 layout 变更
优先使用 transform 和 opacity 做动效,它们性能更好,且天然支持过渡:
立即学习“前端免费学习笔记(深入)”;
.card {
opacity: 1;
transform: translateY(0);
transition: opacity 0.2s, transform 0.2s; /* ✅ 推荐组合 */
}
.card:hover {
opacity: 0.9;
transform: translateY(-4px);
}










