HTML and CSS Reference
In-Depth Information
<p> I should be red because I am the first child in the body. </p>
<p> I should not be red because I am the second child in the body. </p>
<p> I should be red because I am the first child of div. </p>
<p> Second child of div, thus not red. </p>
CSS3 introduces a multitude of document tree-related pseudo-classes. To complement
: first-child() , we now have :last-child() , so
ul li:last-child {background-color: black; color: white;}
would make the last list item in an unordered list have white text on a black background.
You are not limited to looking just at the first or last child of an element. You can also
look at the : nth-child() . For example,
ul li:nth-child(5) {font-size: xx-large;}
would make the fifth list item very large if the list had a fifth item. Of course, such syntax
means that :nth-child(1) is the same as :first-child , which is of course much more
The : nth-child() selector is quite powerful because you can use simple keywords like
odd and even to alternate every other child. For example,
ul li:nth-child(odd) {color: red;}
ul li:nth-child(even) {color: blue;}
would make all odd children in a list red and all even ones blue.
Now suppose you want to make every third element in this unordered list italic; you
could use a rule like
ul li:nth-child(3n) {font-style: italic;}
We can also perform these actions from the end of a tree to look for the last child of a
particular element. For example,
ul li:nth-last-child(2) {text-decoration: underline;}
would make the second-to-last item in the list underlined. Given this syntax, :nth-last-
child(1) is the same as :last-child , which is obviously preferable. We can use all the
same keywords and counting values in the :nth-last-child() pseudo-class as we did in
:nth-child() .
We can also look for elements of particular types within a subtree. For example,
p span:first-of-type {color: red;}
p span:last-of-type {color: green;}
Search WWH ::

Custom Search