SCSS mixin中@if语句失效,无法实现每3个li替换为fizz需求
问题原因
- 核心错误为选择器匹配错误:你代码中写的
ul:nth-child(#{$i})作用是匹配父元素(也就是body)下的第$i个ul标签,但你的HTML结构里只有1个ul标签,循环生成的选择器除了i=1的情况外全部无法命中元素,且就算命中ul也不是你要控制的li元素。 - 你需要选中的是ul内的第
$i个li,正确选择器格式为ul li:nth-child(#{$i})。
修正后SCSS代码
@mixin render { @for $i from 1 through 16 { ul li:nth-child(#{$i}) { &::before { counter-increment: number-counter; @if $i % 3 == 0 { content: 'fizz'; } @else { content: counter(number-counter); } } } } } body { counter-reset: number-counter 0; @include render(); } li { list-style-type: none; }
扩展优化(可选)
如果你不需要依赖SCSS循环,也可以用原生CSS伪类直接匹配所有3的倍数的li,代码更简洁,且可适配任意数量的li元素:
body { counter-reset: number-counter 0; } li { list-style-type: none; &::before { counter-increment: number-counter; content: counter(number-counter); } &:nth-child(3n)::before { content: 'fizz'; } }
内容的提问来源于stack exchange,提问作者Gareth
相关产品推荐
相关产品推荐

