With CSS3 still in its implementation phase, as a Web Developer I’m just itching to use it as I’m sure many are. Many of the new properties and selectors are extremely handy and will make the language much more complete and streamlined. Although it’s semi-compatible with some of the more modern browsers out there, the more seasoned browsers still in use don’t and probably will never support the new version of CSS. Of course, by the time it’s fully implemented, the old guys will be out and we won’t need to worry about that anymore… NOT! We’ll still be in the same conundrum when CSS4 comes out and people are still using IE7, FF2 and FF3. Will it ever end?
In the mean time there is a short term solution that can help you take advantage the new selectors in CSS3. By using jQuery, we can harness the power of CSS3 selectors as it understands them fully and it’s compatible with browsers dating back to IE6.
Say for example you want to add alternate row color to a table. You can do that pretty easily with CSS3 by using the :nth-child(odd) selector but even Firefox 3 doesn’t support this one; the only browsers currently supporting this very useful selector are Opera 9.51 and Safari 3.1.2 (at the time of writing). The other ways to do this would be to hard code a class directly in the markup (yuck!) or if the table is PHP generated you could easily add it with a loop. More simply, you could use jQuery!
Here’s how it’s done. In your head tag, you must include the latest version of the Javascript library. Once jQuery is linked, add this bit of Javascript to your head.
$(document).ready(function() {
$(”table tbody tr:nth-child(odd)”).addClass(”odd-row”);
});
With this simple code, every odd tr tag of a table will have the odd-row class added to it. It’s that simple. We can also take advantage of attribute filters. Say you also want to add a class to links to PDF files:
$(document).ready(function() {
$(”table tbody tr:nth-child(odd)”).addClass(”odd-row”);
$(”a[href*='pdf']“).addClass(”pdf-link”);
});
The possibilities are endless (as is usually the case with jQuery). You can see a list of the supported selectors in the jQuery Documentation pages. You can also see these examples in action.
