Styling every 3rd item of a list using CSS?

HtmlCss

Html Problem Overview


Is it possible for me to style every 3rd list item?

Currently in my 960px wide div I have list of boxes which are floated left and are displayed in a 3x3 grid view. They also have a margin-right of 30px, but because the 3rd 6th and 9th list item has this margin it makes them jump down a row making the grid display wrongly

How easy is to make the 3rd 6th and 9th not have the margin-right without having to give them a different class, or is that the only way to do it?

Html Solutions


Solution 1 - Html

Yes, you can use what's known as :nth-child selectors.

In this case you would use:

li:nth-child(3n) {
// Styling for every third element here.
}

:nth-child(3n):

3(0) = 0
3(1) = 3
3(2) = 6
3(3) = 9
3(4) = 12

:nth-child() is compatible in Chrome, Firefox, and IE9+.

For a work around to use :nth-child() amongst other pseudo-classes/attribute selectors in IE6 through to IE8, see this link.

Solution 2 - Html

You can use the :nth-child selector for that

li:nth-child(3n) {
 /* your rules here */
}

Solution 3 - Html

Try this

box:nth-child(3n) {  
     ...
}

DEMO

nth-child browser support

Solution 4 - Html

:nth-child is the answer you are looking for.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGezzamondoView Question on Stackoverflow
Solution 1 - HtmldsgriffinView Answer on Stackoverflow
Solution 2 - HtmlSirkoView Answer on Stackoverflow
Solution 3 - HtmlZoltan TothView Answer on Stackoverflow
Solution 4 - Htmlhienbt88View Answer on Stackoverflow