HTML and CSS Reference
In-Depth Information
The pseudo-class :first-child is used to select elements that are the first children of
other elements. Consider the following markup:
<div>
<p>These are the necessary steps:</p>
<ul>
<li>Insert key</li>
<li>Turn key <strong>clockwise</strong></li>
<li>Push accelerator</li>
</ul>
<p>
Do <em>not</em> push the brake at the same time as the accelerator.
</p>
</div>
In this example, the elements that are first children are the first p , the first li , and the
strong and em elements. Given the following two rules:
p:first-child {font-weight: bold;}
li:first-child {text-transform: uppercase;}
…you get the result shown in Figure 1-27 .
Figure 1-27. Styling first children
The first rule boldfaces any p element that is the first child of another element. The
second rule uppercases any li element that is the first child of another element (which,
in HTML, must be either an ol or ul element).
As has been mentioned, the most common error is assuming that a selector like p:first-
child will select the first child of a p element. However, remember the nature of pseudo-
classes, which is to attach a sort of phantom class to the element associated with the
pseudo-class. If you were to add actual classes to the markup, it would look like this:
<div>
<p class="first-child">These are the necessary steps:</p>
<ul>
<li class="first-child">Insert key</li>
<li>Turn key <strong class="first-child">clockwise</strong></li>
<li>Push accelerator</li>
</ul>
<p>
Do <em class="first-child">not</em> push the brake at the same time as the
accelerator.
</p>
</div>
 
Search WWH ::




Custom Search