Getting to Know CSS3 Selectors, Part 1: Structural Pseudo-Classes
Emily P. Lewis | August 1, 2012
Today’s front-end developers don’t just need to understand how to write CSS, we need to know how to write it efficiently. And what “efficiently” means can depend on your project and environment. Perhaps you have a team with several members working in the CSS and you need an efficient way to work together. Or maybe you have a huge enterprise site and you need your CSS optimized for speed. You could even be working with a legacy system that restricts access to HTML, which means you need efficient selectors to effectively style elements without ids or classes. You might even face all these situations and more.
Whatever your goals for CSS are, the best way to reach them is to know your options, and that means understanding all the selectors available to you. Most of us are already familiar with id and class selectors, and I introduced you to the beauty of attribute selectors in “ Understanding CSS Selectors.” But there’s so much more.
In this two-part series, I’ll look at the new selectors in CSS3, starting with structural pseudo-classes.
What’s a Pseudo-Class?
CSS pseudo-classes target elements that can’t be targeted with combinators or simple selectors like id or class. You use pseudo-classes to select elements based on their attributes, states, and relative position. For example, you are probably already familiar with pseudo-classes for link states:
CSS3 introduces a number of new pseudo-classes, including structural pseudo-classes that target elements according to their position in the document tree and relation to other elements. Here’s a list of the structural pseudo-classes you’ll see examples of in this article.
Before we look at the details, let’s touch briefly on the syntax you use with pseudo-classes.
The syntax for pseudo-classes uses a colon (:) followed by the pseudo-class name:
If you want to target a specific element (e), you append that element to the beginning of the pseudo-class syntax:
You can even use pseudo-classes alongside id and class selectors, as you see here:
Some of the CSS3 pseudo-classes target elements on the basis of the elements’ specific location in the document tree. You indicate the position with a numeric value in parenthesis (n) appended to the pseudo-class name:
The value of (n) can be an integer to indicate an element’s position in the document tree. The following example targets the third element that meets the pseudo-class rule:
You can also specify numeric formulas, such as “every fifth element,” which is indicated as a value of (5n):
Additionally, you can specify an offset formula (negative values allowed; default is zero) by adding (+) or subtracting (-) the offset value:
These new selectors also allow you to target elements by their document tree order with the keywords odd and even. For example, if you want to target the odd-numbered elements, use the following:
Putting Pseudo-Classes to Work
Now that you’ve seen the general syntax, let’s look at some of the new selectors in more detail and see examples of the style effects you can achieve by using them.
The :root pseudo-class targets the root element—the html element. Consider the following basic markup for a page:
If you want to apply a main background color to this page, with a different background color to show a “container,” you could do this with CSS only and no new markup, as shown here:
In this example, I applied the background color to the html element via :root and applied the styles for the container via a type selector for body. This results in the simple visual layout shown in Figure 1.
The :only-child pseudo-class targets an element that is the only child of its parent. That means the parent element contains only one other element. The :only-child pseudo-class is different from the :root pseudo-class, which assumes the html element. You can use :only-child to target any element by appending the pseudo-class syntax to the element (e), like this:
For example, perhaps you have a block of text in which you promote a new item:
If you want to style the text “Available Now” as a callout, you could use :only-child to target the b element, which is the only child of the h2. Figure 2 shows the code you would use.
Figure 2 Use the :only-child pseudo-class to callout and emphasize text within a heading.
This CSS results in the visual callout seen in Figure 3, which doesn’t need any id or class attributes added to the HTML.
The :empty pseudo-class targets elements that don’t have any children or any text—an empty element such as:
Personally, I can’t think of a situation when I would allow an empty element to be rendered on a site, but that doesn’t mean there isn’t an edge case. In terms of syntax, you could target every empty element with the pseudo-class on its own:
Or, as in the example of the :only-child pseudo-class, you can target a specific element, like td:
This is the first pseudo-class I’m covering that takes advantage of the numeric values described earlier. The :nth-child pseudo-class targets a child element in relation to its position within the parent element. A list of blog comments, for example, might look nice with alternating background colors, as in Figure 4.
The HTML for this example is just an ordered list, as shown in Figure 5.
Figure 5 The HTML for the blog post example.
To style this markup, I first target the list items with a simple type selector, as shown in Figure 6:
Figure 6 Styles for the blog post example.
Then, using the :nth-child() pseudo-class, I target the even-numbered list items:
The :nth-last-child(n) pseudo-class works just like :nth-child(n), except the order is determined in relation to the last child element, rather than the first. Using the same blog comments example, consider the content within each list item:
Each of the paragraph elements that comprise the comment need to be uniquely styled, as does the image. (See Figure 7).
For the commenter name and link, I use the :nth-last-child(n) pseudo-class with a numeric value to target the second-to-last paragraph within the list item:
The :first-of-type pseudo-class targets the first of a specific type of element within a parent. In the blog comment example, I can target the date content as the first paragraph within the list item:
Using :first-of-type, I style the first paragraph (containing the date) to be right-justified with a bottom border:
The :last-of-type pseudo-class targets just what the name says: the last element type within a parent. In the blog example, I can style the comment text in the last paragraph like this:
In Figure 7 you can see how I used :last-of-type to style the last paragraph. Here is the CSS I used:
The :only-of-type pseudo-class targets a child element that is the only one of its type within the parent element. Continuing with the blog comment example, you can use this selector to target the avatar:
The :nth-of-type(n) pseudo-class works similarly to the other numeric-based pseudo-classes I’ve covered. This pseudo-class targets a specific element type according to its position relative to the parent element. You can see an example of the effects you can achieve in the simple shopping cart view shown in Figure 8.
The HTML for this cart, listed in Figure 9, is in a table. (Remember that tables are fine for data but please avoid them for layout).
Figure 9 The HTML for the shopping cart.
To style several of these table elements, I use the :nth-of-type(n) selector to style the text alignment of the table header and data cells. For example, the Item table header cell needs to be aligned left (the default is centered).
With the :nth-of-type(n) selector, you can target that specific child:
I can use the same pseudo-class to style the remaining text alignment needed, without a single class or id:
The :nth-last-of-type(n) pseudo-class works just like :nth-of-type(n), but the relative position is offset from the last child rather than the first. In the shopping cart example, the Subtotal, Tax, Shipping and Total rows need unique styles, as shown in Figure 10.
Let’s look at the Subtotal row, which is the fourth row (tr) from the bottom in the table:
I used :nth-last-of-type(n) to give this row of cells the style seen in the figure. This is the CSS I used:
And I continued with this pseudo-class for the remaining rows of the table:
The :first-child pseudo-class targets the first child element, regardless of type, in a parent element. For this example, let’s consider a sidebar that has a series of content elements (Figure 11).
The markup I used for this example is a containing div, with nested aside elements, which is shown in Figure 12.
Figure 12 Markup for the sidebar
As you can see in Figure 11, the sidebar contains sections of content that have a defined border and background:
However, the first aside contains social media icons and lacks a border and background (see the top of Figure 11). I used the :first-child pseudo-class to target this first section of content:
The :last-child pseudo-class is the opposite of :first-child, targeting the last child element within a parent. Going back to the sidebar example shown in Figure 11, the first section contains a list (ul) of social media links:
Each of these links is rendered on the screen as a different icon, achieved with a simple image-replacement technique and sprites:
In order to style the last link in the list, I use the :last-child pseudo-class:
The remaining middle link is styled with the :nth-child() pseudo-class:
The good news is that all the latest browser versions, including Internet Explorer 10 and 9, support these CSS3 pseudo-classes. Some older browser versions may provide limited support for a few of the CSS3 selectors in this article.
When it comes to support in earlier version of Internet Explorer, it really should be about your project. How are you using any unsupported selectors? If it is purely for design and aesthetic purposes, ask yourself whether you can allow those Internet Explorer users to have a slightly degraded experience, while allowing Internet Explorer 9 and other browser users to have an enhanced experience. If the answer is yes, consider focusing on an adaptive approach to your CSS.
If you need earlier versions of Internet Explorer to support your CSS3 pseudo-classes, check out Selectivzr, a JS utility that emulates CSS3 pseudo-class support in Internet Explorer. It works with jQuery, Dojo, MooTools and Prototype.
The (sorta) bad news about browsers and CSS3 pseudo-classes is that in terms of how efficiently browsers process selectors, pseudo-classes fall to the bottom of the list. If performance and speed are paramount for your project, you should use pseudo-classes judiciously. I recommend taking advantage of some testing tools to help you best optimize your CSS selectors. Some good ones are:
Knowing When and What to Use
So how do you decide which selectors to use? The answer depends on your project. Knowing both your project and the CSS selectors available will help you decide. The CSS3 pseudo-classes I covered in this article may not be the “bread and butter” selectors for your stylesheets, but they can be invaluable tools, particularly for cases when you can’t rely on id and class selectors. Remember, writing good CSS is about finding the most efficient way to achieve a project’s goals.
Keep your eye out for Part 2 of “ Getting to Know CSS3 Selectors.” In that article, I’ll cover UI element state pseudo-classes as well as the :target and negation pseudo-classes.
About the Author
Emily Lewis is a freelance web designer of the standardista variety, which means she gets geeky about things like semantic markup andCSS, usability and accessibility. As part of her ongoing quest to spread the good word about standards, she writes about web design on her blog, A Blog Not Limited, and is the author of Microformats Made Simple and a contributing author for the HTML5 Cookbook. She’s also a guest writer for Web Standards Sherpa, .net magazine and MIX Online.
In addition to loving all things web, Emily is passionate about community building and knowledge sharing. She co-founded and co-manages Webuquerque, the New Mexico Adobe User Group for Web Professionals, and is a co-host of the The ExpressionEngine Podcast. Emily also speaks at conferences and events all over the country, including SXSW, MIX, In Control, Voices That Matter, New Mexico Technology Council, InterLab and the University of New Mexico.
Find Emily on: