treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] nth-child(3n+2)

  • So I have a puzzle, (at least it has been puzzling me) regarding nth child.

    I have rows containing three < section >. On each row the center section has margins assigned to it spacing them out nicely.

    I used the following to do this...

    section:nth-child(3n+2) { margin-right: 20px; margin-left: 20px; }

    This works when there is more than one row. However... if there is only one row the margins get assigned to the third "section" bunching up the first two sections.

    See it working with multiple rows...

    See it not working with only one row...

    Why is this happening? Is there a CSS genius in the house who can shed light on the issue?

  • From this very own site (http://css-tricks.com/the-difference-between-nth-child-and-nth-of-type/):

    Our :nth-child selector (p:nth-child(2)), in "Plain English," means select an element if:
    - It is a paragraph element
    - It is the second child of a parent

    The issue doesn't come from rows but from the number of children inside the parent.
    On your "multiple rows" example, there are only <section> elements in the parent (.homepage) so everything is right.
    On your "single row" example, there are 2 things before sections (#page and .clear). This mess up your :nth-child(3n+2).

    You may want to try using :nth-of-type(3n+2) instead. ;)

  • Thanks Hugo! I clearly need to do some more reading on this. This has fixed the issue.

  • The main difference between :nth-child() and :nth-of-type is the "repository" (not sure if it's the good word for it).

    :nth-child() is the position of the element inside its parent.
    :nth-of-type() is the position of the element among other elements of the same type inside its parent.