CSS3: nth-child selector

In late-February I discovered that neat jQuery trick that adds an alternating background color to a web table that I had constructed. By taking advantage of the :odd and :even selectors, I was able to effortlessly add a class to every other table row to make my table easier to scan. Well, who knew that CSS could do that, too?!

Last week I discovered the nth-child selector, thanks to Lynda.com’s CSS Core Concepts tutorial, which covers nth-child selectors in one of its chapters. I was able to remove this script from the bottom of my document:

        $(function(){
            $("tr:odd").addClass("altTr");
        });

And add this style to the top of my document:

tr:nth-child(2n+1){
    background:#ddd;
}

They do the exact same thing, but now I have less JavaScript on my page to worry about. Be warned that the nth-child selector may give you trouble in IE versions earlier than 9.

To learn more about the nth-child selector and try it out for yourself, check out w3school’s tutorial and practice. And to see what page I’ve been editing lately for the Alaska State Library, go to http://library.alaska.gov/asp/Alaska_Glaciers.html. You may learn a thing or two about glaciers in Alaska, as well!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s