How can I access 2-in-2 items in my list using the: nth-child () parameter, or is it easier to access and customize even items?
How can I access 2-in-2 items in my list using the: nth-child () parameter, or is it easier to access and customize even items?
You can set your pseudo selector nth-child
by adding the even or odd rule ( odd
or 2n+1
and even
or 2n
) to customize the elements.
To customize customizing the even items would be:
li:nth-child(even) {
// Seus estilos
}
Or else:
li:nth-child(2n) {
// Seus estilos
}
I have prepared a JSFiddle to observe this behavior: link
Take a look at the documentation for this pseudo-select to see all the possible combinations you can do: link .
To customize only the even items you would use the following pseudo-selector,
li:nth-child(even){} ou li:nth-child(2n){}
To customize only the odd items you would use this one,
li:nth-child(odd){} ou li:nth-child(2n+1){}
The function that the nth-child
pseudo-selector accepts is An+B
(being An
or B
optional), what do you mean?
When you put the value of (2n+1)
, automatically the CSS does the calculation, say n
assumed the value of 0
(zero), then (2 * 0 + 1) = 1
(two times zero equals zero, the result plus one equals one), then it would apply the declared styles to the first item in its list, then the n
is incremented and becomes the value of 1
(one), then (2 * 1 + 1) = 3
(two times one is equal to two, the result plus one equals three), then it would apply the declared styles to the third item in your list and so on, so the formula (2n+1)
selects the odd elements. / p>
The formula (2n)
will do the same process, only, without the sum. In the first run the n
assumes the value of 0
(zero), then the calculation is done: (2 * 0) = 0
(two times zero equals zero), since there is no zero item in the list, that value is disregarded and n
is incremented by passing 1
(one), then (2 * 1) = 2
(two times one equals two), then the declared styles are applied to item two of your list, and so on, for the fact if you do not add 1
to the multiplication result, the final value will always be an even number, making the formula (2n)
only select even elements.
Note that for the (2n)
formula I have omitted the B
element of the function. All two elements are optional, so I can omit the element An
of the function and simply declare the element B
, as follows: li:nth-child(5){}
, as in this selector there is no calculation to be done, then the declared styles are applied to the number item you declared, in this case only the 5
item will be stylized.