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

CSS过渡(transition)必须写在元素的默认(非: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,不指定属性,默认不生效(部分浏览器可能有兼容行为,但不可靠)display: none 切到 block,或涉及 height: auto,这些本身不支持过渡,需换用 opacity、max-height 或 transform 等可动画属性transition: all 0s 或单位缺失(如写成 300 而非 0.3s)优先使用 transform 和 opacity 做动效,它们性能更好,且天然支持过渡:
立即学习“前端免费学习笔记(深入)”;
.card {
opacity: 1;
transform: translateY(0);
transition: opacity 0.2s, transform 0.2s; /* ✅ 推荐组合 */
}
.card:hover {
opacity: 0.9;
transform: translateY(-4px);
}以上就是css过渡写在hover里不生效怎么办_应写在默认状态而非hover的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号