W3C home > Mailing lists > Public > www-style@w3.org > November 2015

Re: [nth-child(x) bug] nth-child does not correctly select an element with parent

From: Tab Atkins Jr. <jackalmage@gmail.com>
Date: Sat, 28 Nov 2015 17:04:42 -0800
Message-ID: <CAAWBYDB=cggtJA-WH3wq3KTVHNmLLbtcVPJE-Xk3HLTyxZy6Dg@mail.gmail.com>
To: Daniel James <dtj2727@gmail.com>
Cc: www-style list <www-style@w3.org>
On Wed, Nov 25, 2015 at 2:23 PM, Daniel James <dtj2727@gmail.com> wrote:
> Hello, I think I've found a bug or something within the CSS3 spec relating
> to nth-child that is incorrect and doesn't make sense when put into
> practical use. I've checked other browsers to make sure it's not a browser
> bug and the same behaviour occurs in Chrome (latest), Firefox (latest) and
> Internet Explorer (11).
> The issue is that if you use for example:
> .parent input:nth-child(1)
> If inside the parent element is something like a label before the first
> input element, then everything you have put within that CSS selector above
> will not work.
> This is because as far as nth-child is concerned, the first input is not the
> first child of the parent. However we're not looking for anything other than
> the first input child of the parent element.
> I've created a demonstration in case I've not explained it very well. I
> believe this current behaviour is incorrect and should be revised as it's
> not literally doing what you're telling it to do.
> http://codepen.io/anon/pen/epwNKv?editors=110
> I've found that using :nth-of-type is a suitable work around for this issue
> anyway.

Correct, :nth-child() matches an element if it is the nth child.  It
doesn't care about anything else - selectors don't interact with each
other.  :nth-of-type() specializes the function to only count elements
of the same type.

Selectors 4 defines an extension to :nth-child() to let it only count
elements matching an arbitrary selector
<https://drafts.csswg.org/selectors/#the-nth-child-pseudo>, but I
don't think that's implemented anywhere yet.  If it was, you could
write your selector like:

.parent :nth-child(1 of input)

As long as you're only selecting based on tagname, tho, :nth-of-type()
does exactly the same thing and is already widely-implemented, so it
looks like you can just rely on that.

Received on Sunday, 29 November 2015 01:05:31 UTC

This archive was generated by hypermail 2.4.0 : Friday, 25 March 2022 10:08:58 UTC