Skip to main content

:nth-child structural pseudo-class selectors

There are 4 pseudo-class expressions that are part of the :nth-child pseudo-class. Structural pseudo-class selectors target HTML elements based on the DOM tree. Basically, elements that cannot easily be targeted by simple selectors or combinations of selectors. What makes pseudo-classes so handy is the ability style elements dynamically based on its position in the DOM.
  1. :nth-of-type(N)
  2. :nth-last-child(N)
  3. :nth-child(N)
  4. :nth-last-of-type(N)

:nth-of-type(N) selector

My favorite of the 4 is the :nth-of-type(N) selector. The nth-of-type selector allows you to select child elements of a parent based on the particular type of the element, for example every 5th "li" element in a list. You can select even or odd elements, or the nth (order number) child in the group of elements. The class accepts the argument "n" which can can be a keyword, a number, or strings "odd", "even", or an expression "-n+3".
Let's look at a simple but effective use of the nth-of-type selector. If for example you have a table of data that will be pulled from a database and the number of rows is not known before hand. You need to colorize or highlight every other row of the data. Here is our table:

 <table id="typeTableExample" border="1" width="400">
            <tr>
                <th>Name</th>
                <th>Address</th>
            </tr>
            <tr>
                <td>Fred</td>
                <td>1310 VM street</td>
            </tr>
            <tr>
                <td>Phil</td>
                <td>2600 s 3rd st</td>
            </tr>
            <tr>
                <td>John</td>
                <td>44 south Pine</td>
            </tr>
            <tr>
                <td>Chase</td>
                <td>26 second ave</td>
            </tr>
        </table>

Here is our non styled table.

Here we add the nth-of-type selector to the CSS which gives every odd row a background color of #fff and every even row a background color of #c3fdb8.
 
<style type="text/css">

#typeTableExample th{
    background: #ccc;
}

#typeTableExample tr:nth-of-type(odd){
    background: #fff;
}

#typeTableExample tr:nth-of-type(even){ 
    background: #c3fdb8;
}

#typeTableExample tr>td:first-of-type{ 
    font-weight: bold;
}

</style>
Here is our styled table.

In the above example we also added the "first-of-type" attribute to bold the text in the first instances of the "td" tag found that is a child of the "tr" element. The "first-of-type" is equivalent to :nth-of-type(1). The first-of-type matches the first child element of the specified element type.

:nth-last-child(N) selector

The nth-last-child(n) selector matches every element that is the nth child of its parent starting from the last element. Basically, matches elements of their positions within a parent element. Lets extend our table example to make the font color red for the last 3 items in the tabel.
<style type="text/css">

#typeTableExample th{
    background: #ccc;
}

#typeTableExample tr:nth-of-type(odd){
    background: #fff;
}

#typeTableExample tr:nth-of-type(even){ 
    background: #cfdbB8;
}

#typeTableExample tr>td:first-of-type{ 
    font-weight: bold;
}

#typeTableExample tr:nth-last-child(-n+3){
 color:#ff3300;
}

</style>
    
Here is our styled table.

:nth-child(N) selector

The :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent. In our table example we now will make the first table row orange.
<style type="text/css">

#typeTableExample th{
    background: #ccc;
}

#typeTableExample tr:nth-of-type(odd){
    background: #fff;
}

#typeTableExample tr:nth-of-type(even){ 
    background: #c3fdb8;
}

#typeTableExample tr>td:first-of-type{ 
    font-weight: bold;
}

#typeTableExample tr:nth-last-child(-n+3){
 color:#ff3300;
}

#typeTableExample tr:nth-child(-n+2) {
 background:orange;
} 

</style>
 
Here is our styled table

:nth-last-of-type(N) selector

The :nth-last-of-type(n) selector matches every element that is the nth child, of a particular type, of its parent, counting from the last child. Here we will add a red background to the 2nd "li" element from the bottom.
<style type="text/css">

li:nth-last-of-type(2){
 background:#ff3300;
} 

</style>

<ul>
<li>First item.</li>
<li>Second item.</li>
<li>Third item.</li>
<li>Fourth item.</li>
</ul>
Here is our styled list

Known issues

Sadly, Internet Explorer (up until version 8) has no support for structural pseudo-classes. All other modern browsers Firefox, Safari, Chrome and Opera support pseudo-classes.
For IE browsers I would investigate a JavaScript support library such as Selectivizr http://selectivizr.com/ or YUI http://developer.yahoo.com/yui/selector/.
The Selectivizr utility library adds support for CSS3 pseudo-classes in IE. Keep in mind Selectivizr needs the strict mode DTD to work, if you are in Quirks mode you are out of luck. Additionally, the YUI library has JavaScript support for the Pseudo-classes selector syntax: var nodes = YAHOO.util.Selector.query('ul li:first-child');

For more information:

http://reference.sitepoint.com/css/understandingnthchildexpressions

Comments

Popular posts from this blog

Maine summer 2014 photo shoot

Wells Maine beach drive I made a trip up to Wells-Ogunquit Maine last year for my vacation. I was fascinated with the coastal rock formations along the beaches that other photographers had posted throughout the web. I wanted to try my hand at capturing the dawn light and the sunlight reflecting off of the rocks with a long exposure time. In addition, some much needed away time to ride my bike and read. Marginal Way Day one consisted of scouting locations. Perhaps a quick bike ride or beach outing followed by a lobster sandwich. After unpacking I took my bike out through the streets of Wells Maine. I was struck by how similar it was to the town in the movie Jaws Martha's Vineyard. Wells is a small town with narrow streets and older homes. The beach drive featured a fantastic stretch of road just perfect for biking. After a great seafood dinner I scouted the Marginal way.  A combination of site seeing and shooting with the iPhone.  I really underestimated the amount ...

Router modes and channel impairments

What does it mean for a wireless network to be operating in "infrastructure mode?" Clients connected to a base station (an access point or router) are operating in infrastructure mode. They communicate indirectly through this access point or router which serves as a bridge to a wired network. Ad-hoc mode networks are networks that do not rely on a router or access point infrastructure. As a result, each client participates in the routing by forwarding data to the other connected clients. What are the differences between the following types of wireless channel impairments:  path loss, multipath propagation, interference from other sources? Multipath propagation is when packet loss occurs due to electromagnetic waves reflecting off of ground objects which then take paths of different lengths between sender and receiver. Interference from other sources happens when there is interference from radio sources transmitting in the same frequency band. Wireless phones and wirel...

When inspiration happens, what stands in the way?

I was making my way down a wooden walkway on an early morning photo outing - backpack and tripod in hand – when I was struck by this eerie scene that appeared before me.  A perfect moment, I instinctively reached for my iPhone and snapped off this. Had I taken the time to pull the equipment out and set everything up on the tripod, would I have grabbed a better image? Would it have the same wow factor had I used the better equipment? Would I have missed the sun in that particular spot in the sky? At what point does "gear" get in the way of creativity? Should inspiration drive the hardware choices? At a recent photo club outing, the leader was explaining why he continued to use older photography equipment on his hikes. His intention was to always travel light. His tripod was small; it featured no ball head mountings or other bells and whistles, very bare bones. His camera was a point and shoot with an attached lens. He would simply stoop down at an interesting scene and fir...