You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 00:54:01