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

CssCss Selectors

Css Problem Overview


Is is possible to use :not() with 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 .

Css Solutions


Solution 1 - Css

: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.

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.

Demo

Solution 2 - Css

Instead of using "not", the default approach in CSS is to override styles:

td {
    text-align: center;
}
td:first-child {
    text-align: left;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsakhunzaiView Question on Stackoverflow
Solution 1 - CssBoltClockView Answer on Stackoverflow
Solution 2 - CssTiresView Answer on Stackoverflow