CSS动画颜色变化正常但元素位移动画不生效问题求助
问题根源
位移动画失效是非常典型的属性拼写错误:你在div的基础样式里把定位属性position错拼成了postion,少写了字母i,导致定位规则完全没有被浏览器识别。top、left这类位置偏移属性只在元素定位值不是默认的static时才会生效,你写的相对定位因为拼写错误没生效,元素还是默认静态定位,所以关键帧里写的top/left值完全不起作用;而background-color属性不依赖定位,所以颜色过渡能正常运行。
修复方案
只需要把拼写错误的postion: relative;改成正确的position: relative;即可,修正后的完整代码如下:
div { height: 50px; width: 50%; background: blue; margin: 50px auto; border-radius: 5px; position: relative; /* 修正拼写错误 */ } #square { animation-name: first; animation-duration: 4s; } @keyframes first { 0% { background-color: blue; top: 0px; left: 0px; } 50% { background-color: green; top: 25px; left: 25px; } 100% { background-color: yellow; top: -25px; left: -25px; } }
额外提示
- 如果需要动画播放完成后元素停在最后一帧的状态,不跳回初始位置,可以给
#square添加属性animation-fill-mode: forwards; - 调试CSS属性不生效的问题时,可以直接打开浏览器开发者工具的「元素」面板查看对应样式:拼写错误、不满足生效条件的属性会被直接标灰划掉,能快速定位问题。
内容的提问来源于stack exchange,提问作者PrestonGerald
相关产品推荐
相关产品推荐

