添加淡入动画后列表项黑色背景失效问题求助
添加淡入动画后列表项黑色背景失效问题求助
嘿,我来帮你分析并解决这个问题!
问题根源:堆叠上下文的变化
当你给<li>元素添加fadeIn动画后,浏览器会自动为该元素创建一个新的堆叠上下文。在没有动画时,<li>没有独立的堆叠上下文,伪元素::after/::before的z-index: -100是相对于父元素<ul>的,所以伪元素会被<li>的黑色背景覆盖(<li>在<ul>的正常流里,层级比z-index为负的伪元素更高)。
但当<li>拥有堆叠上下文后,伪元素作为它的子元素,层级规则发生了变化:在堆叠上下文内部,元素的背景是最底层,紧接着是z-index为负的子元素,最后才是正常流的内容。这就导致伪元素的锥形渐变会覆盖在<li>的黑色背景之上,所以你看不到黑色背景了!
另外,你的动画代码还有个小bug:先写animation-delay再写animation简写属性,会导致animation-delay被覆盖(简写属性会重置所有动画相关属性),正确写法应该把延迟时间整合到animation属性里。
解决方案:用内层容器承载背景
最直接的解决办法是把<li>里的所有内容包裹在一个内层容器(比如<div>)中,将黑色背景、内边距、边框等样式移到这个内层容器上。这样内层容器作为<li>的子元素,层级会高于伪元素,黑色背景就能正常显示了。
修改后的HTML:
<ul class="prices pricesAnim" style="opacity: 1;"> <li> <div class="card-inner"> <h1>Ofimatica</h1> <ul> <li> <h2>1 hora de uso</h2> </li> <li> <h2>Intel Celeron 12th gen</h2> </li> <li> <h2>8GB RAM</h2> </li> <li> <h2>Paquete office</h2> </li> <li> <h2>Impresion</h2> </li> </ul> <h2>precio: $1000</h2> </div> </li> </ul>
修改后的CSS:
.prices{ list-style: none; display: flex; font-size: 12px; gap: 15px; justify-content: center; padding: 0; opacity: 0; } .prices > li { /* 移除原背景、边框、内边距,交给内层容器处理 */ padding: 0; border: none; display: flex; flex-direction: column; width: calc(100% / 4); align-items: center; text-align: center; justify-content: space-between; position: relative; border-radius: 10px; } /* 新增内层容器样式 */ .card-inner { background-color: black!important; border: 1px solid white; padding: 10px; width: 100%; height: 100%; border-radius: 10px; display: flex; flex-direction: column; justify-content: space-between; align-items: center; } @property --angle{ syntax: "<angle>"; initial-value: 0deg; inherits: false; } .prices > li::after, .prices > li::before{ content: ""; position: absolute; width: 100%; height: 100%; background-image: conic-gradient( #ff4545, #00ff99, #006aff, #ff0095, #ff4545); top: 50%; left: 50%; translate: -50% -50%; z-index: -100; padding: 3px; border-radius: 10px; animation: 3s spin linear infinite; transition: 500ms; } .prices > li::before{ filter: blur(1.5rem); opacity: 0.5; transition: 500ms; } @keyframes spin { from{ --angle: 0deg } to{ --angle: 360deg } } .prices > li ul{ list-style: none; padding: 0; } #prices > h1, #contact > h1, #moreinfo > h1, #about > h1, #footer > h1{ margin: 0; } /* 修复动画延迟的写法 */ .pricesAnim > li:nth-child(1){ opacity: 0; animation: fadeIn 1s forwards 250ms; } .pricesAnim > li:nth-child(2){ opacity: 0; animation: fadeIn 1s forwards 500ms; } .pricesAnim > li:nth-child(3){ opacity: 0; animation: fadeIn 1s forwards 750ms; } .pricesAnim > li:nth-child(4){ opacity: 0; animation: fadeIn 1s forwards 1000ms; } @keyframes fadeIn { 0%{ opacity: 0; transform: translateY(90px); } 100%{ opacity: 1; transform: translateY(0px); } }
这样修改后,内层容器card-inner会显示在伪元素上方,黑色背景就能正常展示,同时动画延迟也能正确生效啦!
备注:内容来源于stack exchange,提问作者Jesús Fernández
相关产品推荐
相关产品推荐

