BASEWEBMASTER

Brought To You By
Tomlin Ventures Ltd

Using Adjacent Selectors

Using Adjacent Sibling Selectors to style with CSS

The adjacent sibling selector is one of the more interesting selectors that CSS has to offer. Although its use may be somewhat limited, when circumstance warrant its use it is invaluable.

Adjacent Selectors Format

An adjacent sibling selector will select an element only when it immediately follows another given element. For example you may wish to select all paragraph element that occur following an h2 element, this would be achieved with the CSS code.

CSS
h2 + p {margin: 0px; padding: 0px;}

Notice the + symbol which is effectively saying adjacent to, this line would select all paragraph elements which occur firstly within the same parent element as the h2 element and secondly occur immediately after the h2 element.

The document tree for the above would look something like this.

adjacent selector

The paragraph element on the right is affected as it occurs within the same parent element namely the div and directly follows the h2 element. The paragraph on the left is not effected because although is appears within the same parent element namely the div it does not in this case follow the h2 element, it follows the unordered list element.

Practical Applications Of The Adjacent Selector

A practical use for this would be to reduce the spacing between the header and paragraph elements, by default a paragraph would appear some distance beneath the header often this is not what you would desire.

By using adjacent selectors it is very easy to change the layout of page elements depending on where they occur and what they follow. Also this can usually be achieved without the use of inline HTML code like ID and class.

Browser Compatability

A quick note about browser compatibility, adjacent sibling selectors are widely supported by all the current major browsers but Internet Explorer 6 and earlier do not support them.

Remember you can always check the browser support for a selector with the browser support table which list all CSS selectors along with their relevant browser support.

Hit the next article button to continue with the tutorial and learn about attribute selectors.

Share to Facebook Share to Twitter Digg This Stumble It Share to Reddit Share to Delicious Technorati LinkedIn Google Buzz Blogger More...

blog comments powered by Disqus