Tuesday, June 10, 2008

The glorious "Adjacent Sibling Selectors"

Ahh, how I love CSS... It truly makes life wonderful! Today I found what I consider to be one of the more elegant of CSS selectors... the "Adjacent Sibling Selectors".

Basically, using the syntax: "E1 + E2{ }", tells the browser to match for the element E1 and E2 within the same parent, directly following each other. It then only applies that style to E2.

For example:

<style>
b + i {font-weight:bold;}
</style>
<span>The <b>Quick</b> <i>Brown</i> <i>Fox</i>

Would render like:
The Quick Brown Fox

instead of:
The Quick Brown Fox

Notice how "Brown" is bold and italicized and "Fox" is only italicized... this is because "Brown" is the child to <i> that is a direct sibling of Quick's <b> while "Fox" is a child to <i> which is a direct sibling to Brown's <i>.


Why would you ever want to do this? Anytime you want an element to act differently only when preceded by a specific element.

For instance, if you have a H1 (Header 1) followed by an H2 (header 2), you might want the H2 to be vertically closer to the H1 than it would be anywhere else on the page. You can accomplish this by simply adding H1 + H2 {margin-top: -5px} to the style sheet.

For more information, check out the W3 specification.

No comments: