Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 560
Chad Avatar asked Mar 01 '11 20:03

Chad


People also ask

How do Nth children choose multiple children?

The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.

How do you select the first 3 children in CSS?

The syntax for selecting the first n number of elements is a bit counter-intuitive. You start with -n , plus the positive number of elements you want to select. For example, li:nth-child(-n+3) will select the first 3 li elements.

How do you target your first and second child in CSS?

The CSS child selector has two selectors separated by a > symbol. The first selector indicates the parent element. The second selector indicates the child element CSS will style.

What's the difference between the nth of type () and Nth child () selector?

The nth-of-type is very similar to the nth-child pseudo-class. The main difference is that it specifically considers the type of the element getting selected before checking any other logic. Let's use our example from above but apply nth-of-type instead.


1 Answers

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

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

However, 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

like image 142
BoltClock Avatar answered Sep 29 '22 11:09

BoltClock