CSS :first-child pseudo-class simple example not working

As far as I can tell, this simple example below should be working but it doesn’t. I’m obviously missing something, but I can’t for the life of me figure it out.

The first .field div should have red text, but it simply does not…

Running Chrome browser on Mac.

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

p .field:first-child {
  color: red;
}
<p>
  <div class="field">first - should be red</div>
  <div class="field">second</div>
</p>

solution

The HTML is invalid.

A p element can’t contain a div element. This results in the following:

<p></p>
  <div class="field">first - should be red</div>
  <div class="field">second</div>
<p></p>

As you can see, the browser is automatically closing the p tags, which explains why your selector isn’t matching anything.


If the HTML was actually valid, then your selector would work. For instance, if you replace the div elements with span elements, the following would work:

Updated Example

p .field:first-child {
  color: #f00;
}