Alternating Styles

Hi,

I been going over various css selector compatibility charts and read a good article about using nth-child pseudo-class to style alternating styles for rows of li’s, divs, etc. Using nth-child(odd) and nth-child(even) seems so much convenient, but since it’s not IE compatible - could there be any other workarounds to styling alternating styles without javascript or additional markup?

Thanks :slight_smile:

If you’re not using CSS nor JavaScript then I don’t see any other way styling your output unless you’re building the HTML code up from a backend server script but that would make your page really slow.

The only way to get it to work reliably across browsers is to manually set a class on alternate items. I guess you could do it with Javascript but it will undoubtedly slow down the rendering of the page and is probably as much work to set up as setting the class manually)

In an ideal world, it would be great to be able to get zebra-striping without any change to the HTML, but realistically, if all you are doing is putting a class on certain elements that are on the page anyway … well, that’s exactly what CSS was designed for, and is perfectly good separation of content and presentation. It’s just a bit more effort…

Guess it’s back to setting alternating class on elements to achieve the effect It’s just that I read a lot of articles about best practices and all comes down to separating the structure of the page from the styles (presentation). Guess in some areas that’s not possible with browsers the way they are.

Hi,
If you can keep up with it in your CSS, you can use the adjacent sibling selector along with some pseudo :first-child styles in IE7+ (not supported in IE6 though)

Neither IE7 or 8 supports :last-child either so that gets eliminated as an option too.

I had put together an example for someone else a while back that uses no classes in the html and everything was styled with pseudo first & last childs along with some sibling selectors.

http://www.css-lab.com/lab-work/hide-text-AP.html

They could not edit the html for some reason or another and they needed to hide alternating paragraphs. That is why all the “p” tags are hanging out on both sides of that demo. They are hanging out because the overflow:hidden; is not engaged on the main div. The reason I have it commented out right now is to show how I styled everything without classes.

If you look at the html you will not find a single class in it, granted it is an extreme example and there is nothing wrong with using some classes. IE7/8 choke on my :last-child styles but just a few classes would salvage that example in IE.

Of course nth-child would have cleaned that CSS up dramatically but the point of it was to show what :first-child and some adjacent sibling selectors are capable of doing.