Monday, November 16, 2009

Adjacent Sibling Selectors

Adjacent sibling selectors allow you to target an element that immediately follows—and that has the same parent as—another element.
      The concept of adjacent sibling selectors may sound a bit convoluted at first, but consider
this example:

<body>
   <h1>This is a header</h1>
   <p>This is a paragraph.</p>
   <p>This is another paragraph.</p>
</body>


      Paragraphs, by default, have a margin of 1 em above and below them. A common style effect is to remove the top margin of a paragraph when it is immediately after a header. The adjacent sibling selector, which is indicated by a plus sign (+), solves this problem for you:

h1 + p {
   margin-top: 0;
}


Although this is incredibly useful in theory, it’s not so useful in the real world. Internet Explorer version 6 and older doesn’t support this selector (Internet Explorer 7 does offer support for it, though). Including it in your styles doesn’t hurt anything—IE will simply ignore it. But those visitors using IE won’t see your adjacent sibling style rules, either.
      This selector doesn’t do a lot for you in the real world at the time of this writing, but it’s still smart to be aware of it, as someday it will come in handy.