120

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?

2
  • For better understanding this issue you can check this tutplus video youtube.com/watch?v=nuCoBOdY2Qk Thanks Commented Dec 23, 2015 at 1:06
  • 3
    You are looking for li:nth-child(3n+3) actually, since you want to exclude index 0. I'm surprised that the correct answer wasn't provided after five and a half years. Here is a JSFiddle Commented Mar 9, 2018 at 22:29

4 Answers 4

271

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.

12
  • does this option work in IE
    – Gezzamondo
    Commented Dec 3, 2012 at 21:11
  • 1
    @Gezzamondo According to MDN it is supported by IE9+.
    – Sirko
    Commented Dec 3, 2012 at 21:14
  • It should work in IE9+. If you're after a work-around for IE8 and before, check this link out - selectivizr.com
    – dsgriffin
    Commented Dec 3, 2012 at 21:15
  • can i use a class on this .work-grid:nth-child(3n) { width:300px; height:300px; margin-right:30px; margin-bottom:30px; background-color:#0C9; float:left; }
    – Gezzamondo
    Commented Dec 3, 2012 at 21:42
  • I can't seem to get this to work. My li's have a class of .work-grid does this mean is cant use the :nth-child() ?
    – Gezzamondo
    Commented Dec 3, 2012 at 22:39
10

You can use the :nth-child selector for that

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

Try this

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

DEMO

nth-child browser support

1
  • +int(Pi/3) for brower support chart!
    – user719662
    Commented Mar 5, 2015 at 18:33
1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.