Css Fury: Part 2 Adjacent Selectors, Transverse Dom With CSS

Scott StultsFebruary 22, 2008

Read Css Fury: Part 1 the star/asterisk selector

One of the “wicked cool” but rarely used parts of CSS selectors is the Adjacent/Sibling Selector . IE 6 does not support this selector. However IE 7, Firefox, and Safari browsers do support this feature. So using this selector can be a good way of using CSS styles to enhance the visual experience while degrading gracefully in older browsers (which gives the user a good reason to update to one that does support CSS 2.1, without affecting the functionality of a site).

An Adjacent Selector basically allows you to select sibling nodes within a given node of the DOM. An example of what an adjacent selector looks like is below.

p + p {
    background: #ccc;
}
<p>I am paragraph one with a normal background. </p>
<p>I am paragraph two with a slightly smoke gray background. </p>

Often times designers rely too heavily on programmers to help with things like using a modulus in order to create alternating styles/classes on rows of a grid or list. In a web site you might see something like if((index % 2) == 0) row.CssClass += " alt"; Well you can do something like this using only CSS within reason, using adjacent selectors. Now do keep in mind, that since CSS is all about cascading and inheritance, that whatever you set on the alternating columns has to be accounted for in the other style set. Meaning if you want to alternate a background color you need to explicitly set the color on both the odd and even rows like below.

ul li,
ul li + li + li,
ul li + li + li + li + li {
     background: #ccc;
}

ul li + li,
ul li + li + li + li,
ul li + li + li + li + li + li {
    background: #999;
}

The above would render something like the list below.

<li style="background: #ccc">
  row 1
</li>
<li style="background: #999">
  row 2
</li>
<li style="background: #ccc">
  row 3
</li>
<li style="background: #999">
  row 4
</li>
<li style="background: #ccc">
  row 5
</li>
<li style="background: #999">
  row 6
</li>

Granted you would not want to do this for something that has more than 10 rows or changes variably, however it does present a solution if you have to style a site that you have limited or no control over the output of the html and you are not allowed to change the semantic markup of a page.

currently listening to..

Grits

The Art of Translation

Here We Go




More blog articles:


We've been Solr-istas since day one!

Our founder wrote the first book on Solr, now in 3rd edition. We've helped organizations from the US Patent and Trademark Office to Cisco build smarter search solutions with Solr.

Learn More about our Solr services.