Bluehost: Web hosting from $3.95/month. Sign Up

Smarter CSS using an adjacent selector

Posted on by Clive Walker in CSS

Wouldn’t it be great if you could add styles to your web page by specifying a style for a particular element on the basis of its proximity to another element? Well, in fact, you can do this using the adjacent-sibling selector!

In this case, proximity means the position in the document tree. The adjacent sibling selector targets an element immediately following another element and that share the same parent. The adjacent sibling selector enables you to selectively target an element without adding a class to that element. Less code in the page. Better style management

For example, you might want to give paragraphs that follow a heading h1 a different style to increase readability; in this case bold. Demo

h1 + p { font-weight: bold;
}

Or you might want to style the first list item in an unordered list differently to subsequent list items. In this case, we use the adjacent sibling selector to apply our style rule to the second and subsequent list items but the first li is unaffected because it is not immediately following another list item. Demo

li + li { color: #F60;
}

You can add a class attribute to your first element if you want to make this more specific. You might use this to style an image description. Demo

img.attractiveimage + p {
	color: #69C;
	font-style: italic;
	margin-left: 50px;
}

The adjacent sibling selector is perhaps not as widely used as it might be but I’m intending to use it more and more.

Note: The adjacent sibling selector is pretty well supported [see Quirksmode and Sitepoint] by most modern browsers. However, in Internet Explorer 7, this selector will also select inappropriate elements in your source code, such as HTML comments. Just make sure that these don’t get in the way. IE 6 does not support the adjacent sibling selector but we’ll soon be dropping support for that browser, right?!

Technorati :

Comments

  • 12 Oct 2008 23:52:44

    “IE 6 does not support the adjacent sibling selector but we’ll soon be dropping support for that browser, right?!” … ah, thanks for the write-up here, I just wish this whole “supporting IE6” were up to the writers of CSS.

© 2016 Clive Walker