Grow your CSS skills. Land your dream job.

Issue with :nth-child()

  • # April 10, 2013 at 1:16 pm

    Hi,

    I am using the **:nth-child()** pseudo selector to target a specific element. There seems to be an issue with the result and I can’t quite figure out how to solve it.

    Below is a simple test case…Essentially the child selector is one element off the intentional target. All elements share the same class name, except for the first…And this seems to be where the nth count is thrown off.

    The goal is to exclude the first element with the different class name…in this case that would be **.top** while targeting one element from the series of **.box** classes.

    **Example:** http://jsfiddle.net/FJ5Y8/

    Is there anyway to go about this properly? Any Help is appreciated.

    Thank you

    # April 10, 2013 at 1:27 pm

    Personally, I’d style all the elements the same, then just target the first element with `:first-child` to change those styles.

    Also, this page helps me alot when trying to calculate `:nth-child` equations: http://css-tricks.com/examples/nth-child-tester/

    # April 10, 2013 at 1:58 pm

    @chrisP

    That could certainly work in some cases…however if you have a look at the example I posted…I need to be able to target specific elements with the class name ‘box’. Ideally it would be nice to exclude the ‘top’ div from the nth count, but if all else fails, simply adding an additional nth number could suffice.

    Thanks for the resource, will have to look at it

    # April 10, 2013 at 2:07 pm

    Unfortunately, you can’t use nth-child to select classes only elements.

    Previously discussed: http://css-tricks.com/forums/discussion/23420/nth-childnth-of-type-bug/p1

    # April 10, 2013 at 2:13 pm

    @paulie_d

    I understand that, but I’m wondering if there is a way to exclude the first element…from the nth count? Are you aware of any methods? The only way I’ve solved that is simply by adding one more to the nth.

    For instance, **.box:nth-child(4){}** will actually target the intended 3rd element with the class of ‘box’

    Example: http://jsfiddle.net/FJ5Y8/1/

    # April 10, 2013 at 2:15 pm

    If there are going to be elements in there that you don’t want to to be counted, you should be using `nth-of-type`.

    # April 10, 2013 at 2:16 pm

    As I said, you can’t apply it to classes…only elements.

    `nth-child` **is** a class (albeit pseudo) and you can’t apply a class to a class.

    EDIT: nth-of-type won’t work either AFAIK…same reason.

    http://codepen.io/anon/pen/fIawL

    # April 10, 2013 at 2:22 pm

    Ok and thank you for the suggestions

Viewing 8 posts - 1 through 8 (of 8 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".