Chad
Chad

Reputation: 3237

CSS nth-child - get 1st, 2nd, 4th and 5th children at once?

With CSS3 I know I can use the nth-child(an + b) selector. I have a table with 5 rows and I would like to select the 1st, 2nd, 4th and 5th rows with one statement. Is this possible or do I have to use a minimum of two statements like this:

:nth-child(-n+2)  /* gets 1 and 2 */
:nth-child(n+4)   /* gets 4 and 5 */

I was hoping for a syntax like nth-child(1,2,4,5) or nth-child(1-2,4-5) but it doesn't appear to be part of the spec.

(I have no control over the page and there are no IDs/classes on these rows.)

Upvotes: 16

Views: 68115

Answers (4)

BoltClock
BoltClock

Reputation: 724462

If you want to be explicit, one way is to repeat :nth-child() like so:

tr:nth-child(1), tr:nth-child(2), tr:nth-child(4), tr:nth-child(5)

Alternately, since the table happens to have exactly 5 rows, you can just exclude the third row and you'll get rows #1, #2, #4 and #5:

tr:not(:nth-child(3))

jsFiddle preview

Upvotes: 30

Arthur Van Passel
Arthur Van Passel

Reputation: 411

You can also use the :is notation if you're using a lot of parents. This is not necessarily a better way, but just looks a bit better imo.

So instead of

.wrapper-class .another-class tr:nth-child(1), 
.wrapper-class .another-class tr:nth-child(2), 
.wrapper-class .another-class tr:nth-child(4), 
.wrapper-class .another-class tr:nth-child(5) {}

You get

.wrapper-class .another-class tr:is(:nth-child(1),:nth-child(2),:nth-child(4),:nth-child(5)) {}

Upvotes: 3

Simona Adriani
Simona Adriani

Reputation: 571

To make it the more generic possible you can use this:

tr:not(:nth-child(1n+6)):not(:nth-child(3))  { 
    /* your rules here */
}

To explain it a little: you are saying you want to select the elements that are not from 6 on (so the first 5) and not 3rd, if you wrote

 tr:nth-child(1n+6) 

you were targeting the rows from 5 on, since you were selecting the rows

(1*0) + 6 [ = 6 ]

(1*1) + 6 [ = 7 ]

(1*2) + 6 [ = 8 ]

...and so on. This is what it means the expression (1n+X), where X in our case is 6.

Adding the :not pseudo selector to the expression above, you are saying you want to select the rows which are not from 5 on, so you will select from 5 down, the 1st, 2nd, 3rd, 4th and 5th.

Plus, adding one more :not selector, which targets the 3rd, you will get what you want => The first 5 without the 3rd!

/***************** UPDATED! I added a jsfiddle *******************/

Here you can see it working in this jsfiddle

Upvotes: 4

Zoheb Akhtar
Zoheb Akhtar

Reputation: 11

You can always use even and odd keywords Like:

table tr:nth-child(even) or if you want the table data use table td:nth-child(odd)

Upvotes: 1

Related Questions