如何实现CSS列表首行共享渐变颜色动画效果?
浏览器起始页分类标题渐变动画实现方案
问题原因
子条目内容不可见的核心原因是gradient类中的-webkit-text-fill-color: transparent属性具有继承性,若将该类添加到了ul这类父容器上,容器内所有子元素都会继承透明文字属性,导致内容不可见。此外原有代码中存在li:first-child规则重复未闭合、固定颜色和渐变属性冲突的语法问题,也会影响样式正常生效。
修正步骤
- 仅给需要实现渐变效果的元素添加
gradient类:页面标题、每个列表的首行分类标题,不要给父级容器添加该类,避免属性继承影响子元素 - 删除CSS中为
li:first-child设置的固定颜色规则,固定颜色会和渐变文字的透明填充属性冲突 - 修正CSS中重复冗余的
li:first-child语法错误,以及过渡属性、阴影属性的书写错误
修正后的核心代码
CSS代码
html { align-items: center; background-color: #191919; color: #c5c8c6; display: flex; height: 100%; justify-content: center; user-select: none; } body { font-family: "Atkinson Hyperlegible"; font-size: 30px; background-color: #191919; display: flex; flex-direction: column; min-height: 30ch; min-width: 50vw; padding: 2em; } p { font-weight: bold; } a { color: inherit; text-decoration: none; position: relative; background-color:transparent; transition: bottom 1s ease; } a:hover { color: #999999; } ul { list-style-type: none; margin: 4px; padding: 8px; box-shadow: 0px 0px 5px 10px #121212 inset; border-radius: 16px; transition: box-shadow 0.2s ease; } ul:hover{ box-shadow: 0px 0px 10px 10px #121212; } span { display: inline-block; color: inherit; box-shadow: 0px 0px 5px 10px #121212 inset; border-radius: 16px; transition: box-shadow 0.2s ease; padding: 8px; } span:hover { box-shadow: 0px 0px 10px 10px #121212; } .gradient { background-image: linear-gradient(90deg, rgba(180,142,173,1) 0%, rgba(191,97,106,1) 12.5%, rgba(208,135,112,1) 25%, rgba(235,203,139,1) 37.5%, rgba(163,190,140,1) 50%, rgba(235,203,139,1) 62.5%, rgba(208,135,112,1) 75%, rgba(191,97,106,1) 87.5%, rgba(180,142,173,1) 100%); background-position: 0px; background-size: 1000px; background-repeat: round; -webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent; text-fill-color: transparent; animation: gradientMove 4s ease-in-out 1; animation-fill-mode: forwards; font-weight: bold; } @keyframes gradientMove{ from {background-position: 0px} to {background-position: 960px} } nav { column-gap: 2em; display: grid; grid-template-columns: auto auto auto auto; padding: 0 0; } li { margin: 8px 0; }
HTML代码(仅展示修改部分)
<body> <p class="gradient"><span>>subject05</span></p> <nav> <ul> <li class="gradient">general</li> <li><a href="#">school</a></li> <li><a href="#">steam</a></li> <li><a href="#">messenger</a></li> </ul> <ul> <li class="gradient">entertainment</li> <li><a href="#">youtube</a></li> <li><a href="#">music</a></li> <li><a href="#">reddit</a></li> </ul> <ul> <li class="gradient">home</li> <li><a href="#">pirate bay</a></li> <li><a href="#">1377x</a></li> </ul> <ul> <li class="gradient">misc</li> <li><a href="#">gmail</a></li> <li><a href="#">cinema</a></li> <li><a href="#">type monkey</a></li> </ul> </nav> </body>
效果说明
修正后仅页面标题和分类标题会显示同步的渐变动画,其他链接文字保持原有样式,hover交互效果不受影响,所有分类标题共享同一渐变动画偏移,不会出现错位问题。
内容的提问来源于stack exchange,提问作者subject05
相关产品推荐
相关产品推荐

