HTML and CSS Reference
Using Advanced Selectors
Chapter 2 introduced you to the 16 most commonly used selectors. Along the way, you've also been introduced to
two more: the :first-child pseudo-class and the child selector. In this chapter, it's time to get up to speed with
the remaining CSS3 selectors. There are another 24 in the CSS3 Selectors module, and even more have already
been proposed for CSS4. You might be wondering why so many selectors are needed.
A fundamental principle behind CSS is the separation of content from presentation. If you rely all the time
on using classes or ID selectors to mark up how your web pages should be presented, the separation begins to
blur. The value of a wide range of selectors is that you can apply styles to elements in specific circumstances
without the need for extra markup in the HTML. To give a simple, yet common example, rows of data in a table
are much easier to read if they have alternate background colors. Until CSS3, the only way to add the colors was
by assigning a class to each alternate row. And if you added or removed a row, you had to reassign the classes
to each row. Thanks to the CSS3 :nth-child() pseudo-class, there's no need for any markup in the HTML. The
colors are applied automatically. There's also a :not() pseudo-class that allows you to apply styles based on a
negative condition. For example, you can create a style that applies to all list items except the first one.
Most of the selectors discussed in this chapter are pseudo-classes. But you'll also learn about additional
attribute selectors, pseudo-elements, and combinators —selectors created by combining two selectors in a
specific way. To make it easy to find information about selectors, this chapter covers not only the remaining 24
selectors from the CSS3 Selectors module, but also the two selectors introduced since Chapter 2, as well as ten
pseudo-classes from the CSS3 Basic User Interface module (CSS3 UI). So, in combination with Chapter 2, this
chapter provides a complete guide to CSS3 selectors.
In this chapter you'll learn about selecting:
First, last, and only instances
Elements based on their position in a series
Elements that appear in combination with another
Elements based on their state
Elements based on a partial attribute match
Most of the selectors in this chapter will not work in IE 8 or older browsers.
Selecting First, Last, and Only Instances
In Chapter 7, I introduced you briefly to the :first-child pseudo-class, which selects an element that is the first
child of its parent. The :first-child pseudo-class is part of CSS2.1, and is supported by all browsers except IE 6.
In CSS3, it has joined the group of closely related pseudo-classes in Table 13-1 that identify the first, last, and only
instances of an element.