CSS 如何使用伪类 :not with :nth-child

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21829478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 01:53:20  来源:igfitidea点击:

CSS how to use pseudo-class :not with :nth-child

csscss-selectors

提问by sakhunzai

Is is possible to use :not()with nth-child?

是可以使用:not()nth-child

I tried something like this without any luck :

我尝试了这样的事情,但没有任何运气:

td:not(:nth-child(4n)){
  text-align:center;
}

However this seems to work :

但是,这似乎有效:

td:not(:first-child){
  text-align:center;
}

What I am trying is to center align all table columns except 2nd and 4th column. The columns are dynamically generated to add a custom class to these column .

我想要的是居中对齐除第 2 列和第 4 列之外的所有表格列。这些列是动态生成的,以向这些列添加自定义类。

回答by BoltClock

:not(:nth-child(4n))will get you anything that isn't :nth-child(4n), i.e. anything that isn't the 4th, 8th and so on. It won't exclude the 2nd child because 2 isn't a multiple of 4.

:not(:nth-child(4n))会给你任何不是的:nth-child(4n)东西,即任何不是 4th、8th 等的东西。它不会排除第二个孩子,因为 2 不是 4 的倍数。

To exclude the 2nd and 4th you need either one of:

要排除第二个和第四个,您需要以下任一项:

  • td:not(:nth-child(2n))if you have fewer than 6 columns, or

  • td:not(:nth-child(2)):not(:nth-child(4))if you have at least 6 columns and only want to exclude the 2nd and 4th, and not every even column.

  • td:not(:nth-child(2n))如果您的列少于 6 列,或者

  • td:not(:nth-child(2)):not(:nth-child(4))如果您至少有 6 列并且只想排除第 2 和第 4 列,而不是每个偶数列。

Demo

演示