{"id":9657,"date":"2011-06-16T04:02:21","date_gmt":"2011-06-16T11:02:21","guid":{"rendered":"http:\/\/css-tricks.com\/?p=9657"},"modified":"2021-06-17T06:06:30","modified_gmt":"2021-06-17T13:06:30","slug":"useful-nth-child-recipies","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/useful-nth-child-recipies\/","title":{"rendered":"Useful :nth-child Recipes"},"content":{"rendered":"\n
I get a little giddy when I come across perfect uses for In these simple “recipes” (really: expressions) I’ll arbitrarily use a flat list of list items and randomly chosen numbers. But it should be fairly obvious how to alter them to get similar selections.<\/p>\n\n\n To select the first element, you can use :first-child, or I bet you can guess how to alter the above to do it as well.<\/p>\n\n\n If there were more than 10 elements here, it would select all of them beyond 5.<\/p>\n\n\n Selects the 10th because we have 10 elements here, but if there was 8 it would select the 8th, or if there were 1,290 it would select the 1,290th.<\/p>\n\n\n Selects the 9th because we have 10 elements here, but if there were 30 elements it would select the 29th.<\/p>\n\n\n Try the tester.<\/a><\/p>\n\n\n Interestingly enough, :nth-child<\/code> or
:nth-of-type<\/code> (read about the difference<\/a>). The better you understand them, the more css nerdgasms you get to have!<\/p>\n\n\n\n
Select Only the Fifth Element<\/h3>\n\n\n
<\/figure>\n\n\n\n
li:nth-child(5) {\n color: green; \n}<\/code><\/pre>\n\n\n\n
Select All But The First Five<\/h3>\n\n\n
<\/figure>\n\n\n\n
li:nth-child(n+6) {\n color: green; \n}<\/code><\/pre>\n\n\n\n
Select Only The First Five<\/h3>\n\n\n
<\/figure>\n\n\n\n
li:nth-child(-n+5) {\n color: green; \n}<\/code><\/pre>\n\n\n
Select Every Fourth, Starting At The First<\/h3>\n\n\n
<\/figure>\n\n\n\n
li:nth-child(4n-7) { \/* or 4n+1 *\/\n color: green; \n}<\/code><\/pre>\n\n\n
Select Only Odd or Even<\/h3>\n\n\n
<\/figure>\n\n\n\n
li:nth-child(odd) {\n color: green; \n}<\/code><\/pre>\n\n\n\n
<\/figure>\n\n\n\n
li:nth-child(even) {\n color: green; \n}<\/code><\/pre>\n\n\n
Select The Last Element<\/h3>\n\n\n
<\/figure>\n\n\n\n
li:last-child {\n color: green;\n}<\/code><\/pre>\n\n\n\n
Select the Second to Last Element<\/h3>\n\n\n
<\/figure>\n\n\n\n
li:nth-last-child(2) {\n color: green;\n}<\/code><\/pre>\n\n\n\n
Wanna play?<\/h3>\n\n\n
Browser Support<\/h3>\n\n\n
:first-child<\/code> was supported by IE 7, but it’s not until IE 9 where the rest of this stuff is supported. Other than IE there isn’t much browser support concern, and if you are worried about IE, then use Selectivizr<\/a>. If browser support stuff is interesting or important for you, definitely check out When can I use…<\/a> which tracks this stuff very well.<\/p>\n","protected":false},"excerpt":{"rendered":"