Fast trick to style a table using CSS3 selectors to set the odd and even rows style:
table > tr:nth-child(even) {background: #ccc;} table > tr:nth-child(odd) {background: #fff;}
So instead of having this:
text more and more text | text more and more text | more and more |
text more and more text | text more and more text | more and more |
text more and more text | text more and more text | more and more |
text more and more text | text more and more text | more and more |
text more and more text | text more and more text | more and more |
text more and more text | text more and more text | more and more |
text more and more text | text more and more text | more and more |
We will have this:
text more and more text | text more and more text | more and more |
text more and more text | text more and more text | more and more |
text more and more text | text more and more text | more and more |
text more and more text | text more and more text | more and more |
text more and more text | text more and more text | more and more |
text more and more text | text more and more text | more and more |
text more and more text | text more and more text | more and more |
You can use those selectors to make the same effect with other element childs like the boxes in your sidebar, or the lis in an ul:
#sidebar > div:nth-child(even) {border-color: #ccc; } #sidebar > div:nth-child(odd) {background: #fff;} ul > li:nth-child(even) {border-color: #ccc;} ul > li:nth-child(odd) {background: #fff;}
Is this cross-browser compatible?
Unfortunately CSS3 is not finished yet and this option doesn’t work in all browsers (Internet Explorer versions up to 8 and older versions from other browsers) so if you want to use this trick for styling your tables in the front end you may like to use jquery instead:
$(document).ready( function(){ $(‘tr’:odd).css({backgroundColor: ‘#ccc’}); $(‘tr’:even).css({backgroundColor: ‘#fff’}); });