CSS :nth-child(n) selector example

:nth-child selector CSS3

The :nth-child(n)  selector matches elements on the basis of their positions within a parent element’s list of child elements.  The :nth-child accepts an argument, N, which can be a keyword, a number, or a number expression of the form an+b.

It is not supported in Internet Explorer 8 (or older) at all. Supporting browsers:

HTML5 browsers support

:nth-child(n) browsers support

Here is quick example to create different color links in a unordered list element.  This example as a fall back for IE8 and less browsers that do not support :nth-child selector (see the code below).

nth-child example in supporting browsers

nth-child example in supporting browsers

nth-child  in non supporting browsers IE8 or less

nth-child in non supporting browsers IE8 or less

DEMO Code:
[php]
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>pseudo-class nth-child example</title>
<style>
<!– set-up list styles and fall back for IE8 and older browsers ->
a {text-decoration:none; color: #FFF;}
ul {list-style:none;}
li a{padding: 3px;
margin: 5px;
display: block;
width: 200px;
background: #00F}
li a:hover{background: #000;}

<!– these styles will work in modern browsers –>
li:nth-child(1) a{background:#00F;}
li:nth-child(2) a{background:#F00;}
li:nth-child(3) a{background:#909;}
li:nth-child(4) a{background:#F30;}
li:nth-child(5) a{background:#090;}
li:nth-child(6) a{background:#369;}
li:nth-child(n) a:hover{background:#000000;}
</style>
</head>
<body>
<ul>
<li><a href="..">example link</a></li>
<li><a href="..">example link</a></li>
<li><a href="..">example link</a></li>
<li><a href="..">example link</a></li>
<li><a href="..">example link</a></li>
<li><a href="..">example link</a></li>
</ul>
</body>
</html>
[/php]

You can find more information on the :nth-child selectors at:
http://www.w3.org/TR/2001/CR-css3-selectors-20011113/

About: Jason Huber

Jason Huber is a multi-disciplinary, award winning web developer specializing application development and user experience.
 

Copyright © Jason Huber .net
This site is mobile ready. How about you?