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.)
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With