SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Jan 2010
    Posts
    16
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Issues with :first-child and nth-child

    Hi there,

    I'm trying to use the :first-child and nth-child selectors but I'm running into the same problem.

    Can someone please explain to me why this works,

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <style type="text/css">
    
    
    #lastyear .polaroid:first-child span{
    	background:red;
    }
    
    
    </style>
    </head>
    <body>
    
    <div id="container">
      <div id="lastyear">
        <div class="polaroid">
          <span>First model</span>
        </div>
      </div>
    </div>
    </body>
    </html>
    but this doesn't,

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <style type="text/css">
    #lastyear .polaroid:first-child span{
    	background:red;
    }
    </style>
    </head>
    <body>
    
    <div id="container">
      <div id="lastyear">
        <span>foo</span>
        <div class="polaroid">
          <span>First model</span>
        </div>
      </div>
    </div>
    </body>
    </html>
    Note, the addition of the child span of #lastyear in the second example.

    Any help would be much appreciated

  2. #2
    billycundiff{float:left;} silver trophybronze trophy RyanReese's Avatar
    Join Date
    Oct 2008
    Location
    Whiteford, Maryland, United States
    Posts
    13,564
    Mentioned
    6 Post(s)
    Tagged
    0 Thread(s)
    Hi, it may be a bit confusing, but the selector you have there basically means this
    Code:
    #lastyear .polaroid:first-child span
    It will select a span that is a parent of .polaroid class, and the .polaroid element HAS to be the first child of #lastyear

    Since the span in the second example makes .polaroid the SECOND child of #lastyear the selector isn't used.

    To test, putting that extra span in the 2nd example, AFTER the .polaroid div will make the selector work . If you don't want to change the HTML of the 2nd example change the selector to last-child (since it's the last there(for now))
    Twitter-@Ryan_Reese09
    http://www.ryanreese.us -Always looking for web design/development work


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
  •