The :first-child CSS pseudo-class is one of the most useful "pseudos" in the CSS spec, allowing us to select the first child element within a parent element. However, against intuition, if you prefix the first-child pseudo-class with an element type, it simply ignores it.

Example:

<div>
  <h3>SubHeading</h3>
  <p>Paragraph</p>
  <p>Paragraph</p>
  <p>Paragraph</p>
</div>

div p:first-child { /* does not select any element above */ }
div :first-child { /* selects the <h3> element */ }

But, what if we want to style the first <p> element without adding any class attributes to the markup? With a little extra CSS, we can actually keep our markup cleaner. If we wanted to create a 3 column layout with the paragraphs above, the CSS would be quite simple if we did not have the <h3> heading preventing us from using the first-child pseudo-class to remove the left margin from the first <p>:

div p { margin-left: 10px; }
div p:first-child { margin-left: 0; }

But, the same can be achieved with little extra effort, even in the presence of the subheading <h3>. It actually might even be more elegant than the above:

div p { float: left; }
div p + p { margin-left: 10px; }

Leave a Reply

Your email address will not be published. Required fields are marked *