CSS实现圆形波浪动画:first-child排序异常及动效相位调试
问题排查与修复方案
核心问题原因
1. 选择器匹配逻辑错误
你使用的:first-child、:nth-child()伪类匹配规则是父元素下所有子元素的排序,而非同class名元素的排序。你当前的<section>标签下第一个子元素是<h2>Challenge 3</h2>,不是.circle元素,所以所有样式匹配全部错位:
.circle:first-child找不到任何符合条件的元素,红色样式完全不生效.circle:nth-child(2)实际匹配到的是第一个.circle元素,所以第一个球变成了黄色- 第五个.circle是
的第6个子元素,你没有写对应的匹配规则,所以用了默认的 antiquewhite背景色,看起来就像你以为的「第一个红色球跑到了最后」
2. 动画方向错误
translateY()的正值代表向下偏移,要实现上移100px的效果,需要改成负值。
修复代码
CSS直接修改方案
.circle { height: 50px; width: 50px; border-radius: 50%; background-color: antiquewhite; animation: circle 1s linear infinite; float: left; margin: 5px; } /* 改用:nth-of-type匹配同div标签的排序,排除h2的影响 */ .circle:nth-of-type(1) {animation-delay: 0s; background: #EF476F} .circle:nth-of-type(2) {animation-delay: -0.2s; background: #FFD166;} .circle:nth-of-type(3) {animation-delay: -0.4s; background: #06D6A0;} .circle:nth-of-type(4) {animation-delay: -0.6s; background: #118AB2;} .circle:nth-of-type(5) {animation-delay: -0.8s; background: #073B4C;} @keyframes circle { 0%, 100% {transform: translateY(0px);} 50% {transform: translateY(-100px);} /* 负值代表向上偏移 */ }
更稳妥的兼容方案(推荐)
给所有小球新增单独的父容器,避免后续父元素新增其他标签时再次打乱匹配规则:
<section> <h2>Challenge 3</h2> <div class="circle-wrapper"> <div class="circle"></div> <div class="circle"></div> <div class="circle"></div> <div class="circle"></div> <div class="circle"></div> </div> </section>
对应CSS就可以直接用:nth-child匹配:
.circle-wrapper .circle:nth-child(1) {animation-delay: 0s; background: #EF476F} /* 其余小球的样式规则同理修改即可 */
内容的提问来源于stack exchange,提问作者Wildog9
相关产品推荐
相关产品推荐

