如何用HTML和CSS实现.bottom-style-p类p元素的依次淡入淡出动画
解决方法
首先修复代码中的核心错误,再调整动画配置实现依次显示+循环重置的效果:
1. 修正无效的动画延迟
你写的 .bottom-style-p:nth-child(1) 中 animation-delay: 2 缺少时间单位s,浏览器会直接忽略这个无效值,导致第一个元素无延迟直接执行动画,和其他元素同步显示。所有动画延迟都必须加上正确的时间单位(如s)。
2. 确保父容器定位正确
给父容器 .bottom-style 添加相对定位,保证所有绝对定位的<p>元素在容器内精准重叠:
.bottom-style { position: relative; }
3. 配置有序动画循环
要实现依次显示后重置,需让每个元素的动画延迟按顺序递增,同时设置动画无限循环。以下是完整可运行的代码示例:
HTML(无需修改)
<div class="bottom-style"> <p class="bottom-style-p">1 / 8</p> <p class="bottom-style-p">2 / 8</p> <p class="bottom-style-p">3 / 8</p> <p class="bottom-style-p">4 / 8</p> <p class="bottom-style-p">5 / 8</p> <p class="bottom-style-p">6 / 8</p> <p class="bottom-style-p">7 / 8</p> <p class="bottom-style-p">8 / 8</p> </div>
CSS(调整后)
.bottom-style { position: relative; } .bottom-style-p { position: absolute; top: 96%; opacity: 0; /* 动画时长4s,无限循环,保留fill模式 */ animation: pFadeIn both ease-in 4s infinite; } @keyframes pFadeIn { 0% { opacity: 0; } 25% { opacity: 1; } /* 前1秒渐显 */ 75% { opacity: 1; } /* 中间2秒保持显示 */ 100% { opacity: 0; } /* 最后1秒渐隐 */ } /* 按顺序设置延迟,每个元素延迟等于前一个元素的动画总时长 */ .bottom-style-p:nth-child(1) { animation-delay: 0s; } .bottom-style-p:nth-child(2) { animation-delay: 4s; } .bottom-style-p:nth-child(3) { animation-delay: 8s; } .bottom-style-p:nth-child(4) { animation-delay: 12s; } .bottom-style-p:nth-child(5) { animation-delay: 16s; } .bottom-style-p:nth-child(6) { animation-delay: 20s; } .bottom-style-p:nth-child(7) { animation-delay: 24s; } .bottom-style-p:nth-child(8) { animation-delay: 28s; }
关键逻辑说明
- 延迟值规则:每个元素的延迟 =
(元素索引-1) * 动画时长,确保前一个元素动画结束时,下一个元素刚好开始,实现无缝衔接的依次显示。 animation-iteration-count: infinite让整个8个元素的动画序列播完后自动重置,开始新一轮循环。- 若想保留你最初的10s动画时长,只需把延迟值改为
(元素索引-1)*10s,同时调整@keyframes里的百分比节点,即可对应实现5秒显示、5秒隐藏的效果。
内容的提问来源于stack exchange,提问作者Chaotic Jiggle
相关产品推荐
相关产品推荐

