8.1 The :first-child Pseudo-class
The :first-child pseudo-class matches a specified element that is the first child of another element. This can be a useful feature but take note that for this to work in Internet Explorer a correct DOCTYPE must be declared. For example, to match the first <p> element that is the first child of any element:
p:first-child {color:blue;}
And no additional markup is required in the HTML document:
<p>Hello World!</p> <p>It's a fine day again.</p>
This would look like this in a browser:
Hello World!
It's a fine day again.
We can also target the first occurances of an element across multiple elements. For example:
p > i:first-child {font-weight:bold;}
And again no additional markup is required in the HTML document:
<p>This may <i>seem</i> hard but it only <i>seems</i> that way!</p> <p>It's actually <i>easier</i> than you may think - <i>believe</i> me!</p>
This would look like this in a browser:
This may seem hard but it only seems that way!
It's actually easier than you may think - believe me!
We can also match all elements that are the first child of another element. For example:
p:first-child i {color:blue;}
And yet again no additional markup is required in the HTML document:
<p>This may <i>seem</i> hard but it only <i>seems</i> that way!</p> <p>It's actually <i>easier</i> than you may think - <i>believe</i> me!</p>
This would look like this in a browser:
This may seem hard but it only seems that way!
It's actually easier than you may think - believe me!