HTML and CSS Reference
In-Depth Information
The first article is the second element on the page. You could select it
with article:nth-child(2) , but that would be a fairly fragile solution—it
would break if someone decided to add an advertising banner between
the header and the first article. Each article starts with an <h1> , but
then one article leads with a picture, and the other leads with a para-
graph. In this case, p:nth-child(2) would only select the last paragraph
in the first article.
It's for situations exactly like these that
we have the :first-of-type pseudo-
article:first-of-type {
background-color: #000;
This selector will always apply to the
first article element on the page, as well
as any other first article elements fur-
ther down the tree. Note that the image
isn't transparent so you can't see the
background behind it.
The last-of-type pseudo-class works in
the same way, except in reverse:
p:last-of-type {
background-color: #000;
If you don't want the last or the first, or
you want to style according to a pattern,
you can use :nth-first-of-type and
:nth-last-of-type . This work in the
same way as :nth-child except that the
only elements that take part in the count
are those specified by the simple selec-
tor to which you apply the pseudo-class.
Search WWH ::

Custom Search