nth-child选择器仅首个元素样式生效问题求助
解决nth-child选择器仅第一个生效的问题
问题根源
你当前的写法逻辑有误:每个<a>标签内只有1个<span>元素,所有<span>都是其父元素(<a>)的:nth-child(1),:nth-child(2)及以后的选择器根本找不到匹配元素,自然不会生效。要区分不同导航项的下划线,应该把nth-child定位到<li>层级——<li>是<ul#subnav>的直接子元素,每个<li>对应一个独立的导航项。
修正后的Sass代码
.container { #subnav { margin-top: 2rem; display: flex; justify-content: space-evenly; li { padding-bottom: 0.5rem; // 修正原代码错误的border写法(需要底部边框可保留) // border-bottom: 4px solid #f36e52; } a { color: #fff; text-decoration: none; span { position: relative; // 给伪元素做定位参照 &:after { content: ''; position: absolute; bottom: -0.5rem; right: 0; height: 4px; } } } // 逐个设置每个导航项的下划线样式 li:nth-child(1) span:after { width: 30%; background-color: #f36e52; } li:nth-child(2) span:after { width: 100%; background-color: #fff555; } li:nth-child(3) span:after { width: 70%; background-color: #42b983; } li:nth-child(4) span:after { width: 50%; background-color: #2196f3; } li:nth-child(5) span:after { width: 80%; background-color: #9c27b0; } } }
关键修改点
- 调整选择器层级:用
li:nth-child(n)定位每个导航项,再设置内部<span>的伪元素样式,精准匹配每一个链接。 - 修正border语法错误:原代码中
border-bottom: 4px 0.5rem; border-color: solid #f36e52;不符合CSS语法,正确写法是合并为border-bottom: 4px solid #f36e52;(不需要可删除)。 - 优化伪元素定位:把
float改为绝对定位,搭配span的相对定位,避免布局偏移,更稳定控制下划线位置。
内容的提问来源于stack exchange,提问作者nodibb
相关产品推荐
相关产品推荐

