Web development by Gabriele Romanato

Post navigation

CSS: the adjacent selector

The CSS adjacent selector is part of the CSS 2 specification. Originally created in 1998, it was firstly implemented in the Gecko-based browsers in late 90s and then adopted by all other standard compliant browsers with the exception of Internet Explorer 6. In its essence, this selector allows you to select an element (or more elements) that came after a given element in the source code. An element is said to be adjacent of another when there are no other elements between them in the document tree. For example, given the following HTML structure:

<ul>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ul>

The second and third item of this list are all adjacent with respect to the first item. So we can write:

ul li + li {
color: green;
font-weight: bold;
}

The adjacent selector comes in the form of a plus sign between two elements. In this case, the second and third list items will get the specified styles. What if we want to stylize only one single element using this selector? In that case we need to give this selector a starting element as a reference, like so:

ul li:first-child + li {
color: red;
font-weight: normal;
}

In this case only the second list item will get its styles, because we've specified as a starting element the very first child of the list (the first item). You can see a test here.

This entry was posted in css by Gabriele Romanato. Bookmark the permalink.