第N个子元素组合跳过2个,然后选择第3个。

7
我想知道这个元素的nth-child()值:

1 2 3 4 5 6 7 8 9 10

我已经在许多参考资料中搜索过,例如:nth TesterMastering the :nth-child,但是找不到我需要的组合。
我还在这个CSS3 :nth-child Calculator上检查了我的组合,它显示的组合如下:
:nth-child(n+3):nth-child(-n+5):nth-child(n+8):nth-child(-n+10):nth-child(n+13)

有人能帮我实现这个吗?

3个回答

7
您可以组合多个nth-child()选择器来实现您的目标:

li:nth-child(5n+3), /* Will select 3, 8, 13, 18...  */
li:nth-child(5n+4), /* Will select 4, 9, 14, 19...  */
li:nth-child(5n+5)  /* Will select 5, 10, 15,20...  */
{
  background:gold;
  border:1px solid green;
}
<ol>
  <li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li>
  <li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li>
  <li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li>
  <li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li>
</ol>


6

web-tiki已经给出了很好的回答,但是你甚至可以更简洁地使用:not()实现:

li:not(:nth-child(5n+1)):not(:nth-child(5n+2)){
    background:gold;
    border:1px solid green;
}
<ol>
  <li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li>
  <li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li>
  <li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li>
  <li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li>
</ol>


嗨,Vucho,感谢你的回答,not()是否支持与第一个答案类似的浏览器兼容性...??这段代码对所有浏览器都兼容吗?? - SaurabhLP
@SaurabhLP 两者都是CC3选择器,因此两个答案在同样的浏览器中都可以工作(在IE8及以下版本中无法工作)- caniuse CSS3 selectors - Vucko
1
li:not(:nth-child(5n+4)):not(:nth-child(5n+5)){...} 将跳过每个第四和第五个元素。 - Vucko

0

li:not(:nth-child(4n+1)):not(:nth-child(4n+0)){
    background:gold;
    border:1px solid green;
}
<ol>
  <li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li>
  <li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li>
  <li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li>
  <li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li>
</ol>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接