How do I use adjacent sibling selectors?
Author: Deron Eriksson
Description: This CSS example demonstrates adjacent sibling selectors.
Tutorial created using: Windows XP


An adjacent sibling selector can be used to select an element that follows another element where both elements share the same parent element. The adjacent sibling elements are separated by a plus (+) sign.

The following HTMLW page demonstrates adjacent sibling selectors. It features two adjacent sibling selectors, 'h1+h2' and 'h2+h1'. The first rule states to turn the text red for an h2 element that follows an h1 element. The second rule states to turn the text blue for an h1 element that follows an h2 element.

style-test.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Style Test</title>
<style type="text/css">
h1+h2 { color: red; }
h2+h1 { color: blue; }
</style>
</head>
<body>
<h1>Howdy One</h1>
<h2>Howdy Two</h2>
<h2>Howdy Three</h2>
<h1>Howdy Four</h1>
</body>
</html>

We can see that 'Howdy Two' is red, since it belongs to an h2 element that follows an h1 element. We can see that 'Howdy Four' is blue, since it belongs to an h1 element that follows an h2 element.

adjacent sibling selectors example

Adjacent sibling selectors work as expected in IE7 and Firefox. Adjacent sibling selectors do not work in IE6.