nth-child
pseudo element. This is specified in a very confusing way so some examples will help clarify its behaviour. The specification states that :nth-child(an+b)
matches those elements that have an + b - 1
preceding siblings, where n
can be any non-negative integer and a
and b
are integers, either negative, zero, or positive.
e.g. if a
is 2
and b
is 1
then elements that have 2n
preceding siblings match, i.e. those element that have 0
, 2
, 4
, ... preceding siblings.
Another way of specifying this that makes it easier to process is that it matches elements that can satisfy the equation p = an + b
, for a non negative integer n
, where p
is the 1
based position of the element within the list of sibling elements.
The above equation is not easy to test in as it requires looping though values of n
until either it matches, or exceeds the position of the elemnt. However, some simple manipulation produces the following equation which while still having the same problem looks simpler to test.
(p - b) / a = n
Unfortunately, the manipulation is not mathematically valid as it does not take into account the fact that a
may be 0
. In this case the original equation reduces to p = b
. If this edge case is dealt with separately then the above equation is valid again.
A further manipulation takes advantage of the fact that if x
, y
and
n
are all integers then x / y = n if and only if x % y = 0
. This means that the above equation can be further reduced to the following which is very simple to test.
(p - b) % a = 0
One additional thing to consider is that if (p - b) / a
is negative then it never matches as n
is non-negative. This will only happen if the sign of (p - b)
is different to the sign of a
. This should be tested before testing the result of the above equation as modulus has some unintuitive behaviour when it comes to handling negative numbers.
The following examples attempt to clarify the effect and possible usage of the different combinations of values. All the examples represent the sequence of child elements as a {@link java.util.List}(sequence
) to illustrate the behaviour.
When a = 0
then b
specifies the position of the matching element. i.e. the only element that matches is sequence.get(b)
.
When a = 1
then b
specifies the position of the first element that matches, and all following elements also match. i.e. the elements that match are sequence.subList(b, sequence.size())
.
When a = -1
then b
specifies the position of the last element that matches, an all preceding elements also match. i.e. the elements that match are sequence.subList(0, b)
.
|
|
|
|