SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict Divisive Cotton's Avatar
    Join Date
    Jun 2008
    Location
    Andy lives in London, UK
    Posts
    393
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Confused about :nth-of-type()

    I understand the CSS 3.0 pseudo-class :nth-child() but I'm confused about how :nth-of-type() is used (or why it is used instead of :nth-child() ) - can anybody give me a practical explanation of how this is used?

    It's the same for
    Code:
    :only-of-type
    I understand
    Code:
    :only-child
    but I don't know why I would use instead
    Code:
    :only-of-type

  2. #2
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,158
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The :nth-child() pseudo-class (and the edge cases :first-child and :last-child) match any child elements.

    The :nth-of-type() pseudo-class (and the corresponding edge cases) match children of a specific element type.

    For instance, if you would like to have special formatting on the first paragraph in a div, regardless of whether it's preceded by a heading, you could use,
    Code CSS:
    div>p {text-indent:1em}
    div>p:first-of-type {text-indent:0}
    Birnam wood is come to Dunsinane

  3. #3
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,158
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Another scenario: let's say you have a lot of text, and that every paragraph has a small photo in it as an illustration. You'd like to float every other photo to the left and the others to the right, to create some 'dynamics' in the layout.

    With CSS2 you'll have to resort to classes for this. With CSS3 you can use the new pseudo-classes:
    Code CSS:
    p.nth-of-type(odd) img {float:left}
    p.nth-of-type(even) img {float:right}
    Headings, lists, etc. between the paragraphs won't break the 'rhythm', like they would if you used :nth-child() instead.
    Birnam wood is come to Dunsinane


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •