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,


<!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,


<!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 :slight_smile:

Hi, it may be a bit confusing, but the selector you have there basically means this

#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)) :slight_smile: