Home > Net >  CSS nth-child: what exactly does nth-child(1n) select
CSS nth-child: what exactly does nth-child(1n) select

Time:10-13

I have been reading this article and it is pretty clear to me so far that something along the lines of: ul li:nth-child(3n 3) will select every 3rd li due to the fact that the "n" within the expression starts at zero and then represents a set of all positive integers; so n = 0, n = 1, n = 2, etc., which in the article I have linked goes on to indicate that indeed :nth-child(3n 3) is tantamount to (3x0) 3 which equals 3, (3x1) 3 equals 6 and so on. I have also seen similar CSS such as: .some-selector:nth-child(1n); .some-selector:nth-child(2n); What I glean from the examples from the aforementioned article leads me to posit that .some-selector:nth-child(1n); would equate to .some-selector:nth-child(0); but this also feels wrong to me. Can someone help me to better understand this? Thanks

CodePudding user response:

Xn essentially means every Xth child, where Xn Y is every Xth child with an offset of Y.

1n is quite nonsensical, as it will just select every child (every 1th child, which essentially is just every child).

2n would be every 2nd child, starting with the second child ([0], 2, 4, 6, 8, 10, ...). Technically this would start with the zeroth child, but there is no such thing in HTML/CSS, so it's functionally equivalent to 2n 2.

2n 1 would be every 2nd child, starting with the first child (1, 3, 5, 7, 9, ...).

You can specify any Y value in Xn Y, so if you wanted your every-other selector to start with the 4th element, it would be 2n 4

You can also specify a number in nth-child to directly select whichever child you want.

CodePudding user response:

Your feeling is correct, :nth-child(1n) does not equal :nth-child(0). A selector with an expression like :nth-child(1n), or actually :nth-child(n) which is the same would select all children. So apparently it wouldn't make much sense...

To understand which elements are going to be selected you have to give n incremental values starting from 0, as in the table in the article you linked, and all the values you get will be the indexes of the selected elements.

There are also some :nth Testers that will help you understand better.

CodePudding user response:

.block:nth-child(1n) will target every element with the class block that is a multiple of 1

So it will result the exact same thing as .block{...}

If you want to select only the first one you can use the following

  • Related