124

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
  • 1
    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

278

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.

Sign up to request clarification or add additional context in comments.

12 Comments

does this option work in IE
@Gezzamondo According to MDN it is supported by IE9+.
It should work in IE9+. If you're after a work-around for IE8 and before, check this link out - selectivizr.com
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; }
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() ?
|
10

You can use the :nth-child selector for that

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

Comments

4

Try this

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

DEMO

nth-child browser support

1 Comment

+int(Pi/3) for brower support chart!
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.