Blog

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

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;}

I am paragraph one with a normal background.

I am paragraph two with a slightly smoke gray background.

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.

  • style="background: #ccc"> row 1
  • style="background: #999"> row 2
  • style="background: #ccc"> row 3
  • style="background: #999"> row 4
  • style="background: #ccc"> row 5
  • style="background: #999"> row 6
  • 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