Here's a little trick I learned today. Think of a table with rows.
Do you think that it's possible to only apply styles to first, let's
say 3, rows using CSS3 selector? Well, it turns out it is possible with
class selector. Let's look at it's basic usage first.
even as an argument value
accepts algebraic expression in format: an+b and executes it in iteration
n starting with
n = 0 until it reaches the end of the
elements tree or until the resulting value is zero or negative.
So, assuming following markup:
.item:nth-child(2n+1) will do something like:
2 * 0 + 1 equals 1 and so first element will be selected
2 * 1 + 1 equals 3 and so third element will be selected
2 * 2 + 1 equals 5 and so fifth element will be selected
2 * 3 + 1 equals 7 and so selector will stop iterating as seventh element
doesn't exist (note that elements index start with
1 and not with
#Now the real stuff
In the end of spec,
there is this note:
The value a can be negative, but only the positive values of an+b, for n≥0,
may represent an element in the document tree.
What this means is that if we pass
-1n+3 or shorter
iteration will happen:
-1 * 0 + 3 equals 3 and so third element will be selected
-1 * 1 + 3 equals 2 and so second element will be selected
-1 * 2 + 3 equals 1 and so first element will be selected
-1 * 3 + 3 equals 0 and so selector will stop as there is no element with
..which results in selecting first 3 elements! Done.
By the way there is a online nth-child simulator which I
personally use when playing with
nth-* selectors. Just FYI.