Re: [css3-selectors] The :nth-sibling combinator

On Fri, Jun 18, 2010 at 9:26 AM, Eduard Pascual <herenvardo@gmail.com> wrote:
>> I stumbled on this problem while viewing a demo on scrollable
>> tables that made a large use of something like the following:
>>
>> span + span + span {}
>>
>> Actually, this may be rewritten using a :nth-child() combinator.
> Can it? If you have a markup like this:
> <div>
>   <span>...</span>
>   <span>...</span>
>   <span>...</span>
> </div>
> then either div>span+span+span or div>span:nth-child(3) would do.
> However, what would happen if you had something like this?
> <div>
>   <span>...</span>
>   <img ... alt="Now things are getting funnier!">
>   <span>...</span>
> </div>
> Then we get a difference between what the selectors would match:
> div>span+span+span matches nothing, while div>span:nth-child(3)
> matches the <span> after the <img>.

The actual equivalent of "span:nth-sibling(3)" is "* + * + span".
Both of these would match the same things in both examples, and in
your example below.


> Now, let's take things even crazier:
> <div>
>   <span>...</span>
>   <span>...</span>
>   <span>...</span>
>   <span>Which selectors shall match this?</span>
> </div>
> Now the fun really begins: obviously, div>span:nth-child(3) will match
> the 3rd <span>, but not the fourth. Less obviously, div>span+span+span
> will match *both* the third and the fourth <span>s! (Did you expect
> it?). As a matter of fact, it's possible to match it with
> div>span:nth-child(3+1n) or something like that (sorry, I'm unsure now
> about the exact syntax). To match only the third <span> with a
> '+'-based selector, the simplest way I can think of would be
> div>span:first-child+span+span

Right, that's the simplest way to match only the 3rd child using combinators.

Also, correct, if you want to match from the 3rd child onward, use
:nth-child(3+n).  (When dealing with any of this family of
pseudoclasses, the elements are numbered from 1 upwards, and "n"
starts at 0 and goes upwards.)

Overall, I believe that this selector is exactly equivalent in terms
of power to the :nth-child() pseudoclass, but appears to be more
confusing to use.

~TJ

Received on Monday, 21 June 2010 17:05:21 UTC