Getting to Know CSS3 Selectors: Structural Pseudo-Classes

Today’s front-end developers don’t just need to understand how to write CSS, we need to know how to write it efficiently. What “efficiently” means can depend on your project and environment.

Perhaps you have a team with several members working with 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. 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:

:link
:visited
:hover
:active
:focus

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.

Pseudo-Class Syntax

The syntax for pseudo-classes uses a colon (:) followed by the pseudo-class name:

:pseudo-class {}

If you want to target a specific element (e), you append that element to the beginning of the pseudo-class syntax:

e:pseudo-class {}

You can even use pseudo-classes alongside id and class selectors, as you see here:

#id:pseudo-class {} .class:pseudo-class {}

Numeric Values

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 parentheses (n) appended to the pseudo-class name:

:pseudo-class(n) {}

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:

:pseudo-class(3) {}

You can also specify numeric formulas, such as “every fifth element,” which is indicated as a value of (5n):

:pseudo-class(5n) {}

Additionally, you can specify an offset formula (negative values allowed; default is zero) by adding (+) or subtracting (-) the offset value:

:pseudo-class(5n+1) {}

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:

:pseudo-class(odd) {}

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.

:root

The :root pseudo-class targets the root element—the html element. Consider the following basic markup for a page:

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 below.

:only-child

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:

e:only-child {}

For example, perhaps you have a block of text in which you promote a new item:

<h2><b>Available Now!</b> Paperback edition of The Zombie Survival Guide: Complete Protection from the Living Dead</h2>

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.

This CSS results in the visual callout seen below, which doesn’t need any id or class attributes added to the HTML.

:empty

The :empty pseudo-class targets elements that don’t have any children or any text—an empty element such as:

<p></p>

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:

:empty {
background-color: red;
}

Or, as in the example of the :only-child pseudo-class, you can target a specific element, like td:

td:empty {
background-color: red;
}

:nth-child(n)

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.

:nth-last-child(n)

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:

You can see how I used :last-of-type to style the last paragraph. Here is the CSS I used:

p:last-of-type {
font-style: italic;
margin: 50px 10px 10px 100px;
}

:only-of-type

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:

:nth-of-type(n)

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 here.

The HTML for this cart is in a table. Remember that tables are fine for data but please avoid them for layout.

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).

<tr>
<th>Quanity</th>
<th>Item</th>
<th>Price</th>
</tr>

With the :nth-of-type(n) selector, you can target that specific child:

th:nth-of-type(2) {
text-align: left;
}

I can use the same pseudo-class to style the remaining text alignment needed, without a single class or id:

:nth-last-of-type(n)

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.

Let’s look at the Subtotal row, which is the fourth row (tr) from the bottom in the table:

<tr>
<td colspan="2">Subtotal</td>
<td>$711.19</td>
</tr>

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:

:last-child

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:

In order to style the last link in the list, I use the :last-child pseudo-class:

li:last-child a {
background-position: -100px 7px;
}

The remaining middle link is styled with the :nth-child() pseudo-class:

li:nth-child(2) a {
background-position: -200px 7px;
}

Browser Support

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.

Processing

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.

In the second part of this article, I’ll cover UI element state pseudo-classes as well as the :target and negation pseudo-classes.

Emily Lewis is a freelance web designer of the standardista variety, which means she gets geeky about things like semantic markup and CSS, usability and accessibility. She writes about web design on her blog and is the author of Microformats Made Simple and a contributing author for the HTML5 Cookbook.

Jon

What’s the advantage of using :root over the html tag directly?

http://www.5sn1.com Mike Earley

From CSS Tricks…”:root – Selects the element that is at the root of the document. Almost certainly will select the html element, unless you are specifically working in some weird environment that somehow also allows CSS. Perhaps XML.”

Alex Walker

Mike I’m guessing that you originally wrote ‘…html element’ but it got pruned on submission. I editted it back in manually, but let me know if you meant something else.

Stevie D

I see Jon has already asked my first question, but I’m still left wondering just how useful these are all going to be. My first impression is that you will end up with lovely clean classless HTML, but CSS will be a tangled nightmare, and will be incredibly inefficient. I’m thinking about :only-child and :only-of-type in particular here. There may be cases where they are useful, but far more often they will just make life more difficult. Why? Because you are then putting more restrictions on the content that can go into sibling elements, to ensure that it doesn’t accidentally trigger the rule that is supposed to be targeting a specific item; because if you’re using pseudo-classes to target specific items then you lose the flexibility to re-order and change the content, without it completely stuffing up the CSS.

Yes, there definitely are cases where pseudo-classes will be very welcome … but there are a lot more cases where you are better off sticking with classes (or occasionally IDs) for your styling rather than sacrificing the CSS to purify the HTML.

Christian

To me they are tools that are there if the need for them arises. If the need doesn’t arise then don’t feel pressured to use them.

“Because you are then putting more restrictions on the content that can go into sibling elements, to ensure that it doesn’t accidentally trigger the rule that is supposed to be targeting a specific item; because if you’re using pseudo-classes to target specific items then you lose the flexibility to re-order and change the content, without it completely stuffing up the CSS.”

There is some truth to that but these pseudo-classes exist for cases where there really is some meaning to an element having a special position in the DOM.

http://www.5sn1.com Mike Earley

I think it’s worth talking about the difference between psuedo classes and pseudo elements, when talking about one or the other. I also think it’s important to note that pseudo elements MUST come at the end of a selector, whereas pseudo classes can be in any order. For example, e:last-child:after is valid, but e:after:last-child is not valid.

Otherwise? This goes into my evernote account, and was a great read, thanks!

http://www.bookings-online.net mezzo

Very useful! Thanks.

Alex Walker

Hey Emily, nice article.

A use-case for ‘:empty’ might be an app that lets you compile playlists. You hit ‘Create New Playlist’ and it adds a new UL and an empty LI to the DOM, with an ‘+’ button at the bottom.

That list might look a little clunky with nothing in it — often your layout is built to look good with something in it — so you could write something like: