Styling every 3rd element of a list with CSS?

Is it possible for me to simulate every third element of the list?

Currently, in my 960px div, I have a list of fields that float to the left and display as a 3x3 grid. They also have a margin-right of 30px , but since the 3rd 6th and 9th list items have this margin, it makes them jump down, making the grid display incorrectly

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

+48
html5 css3
Dec 03
source share
4 answers

Yes, you can use the :nth-child selector.

In this case you should use:

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

: 5th child (3n):

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

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

For working with :nth-child() among other pseudo-class / attribute selectors in IE6 through IE8, see this link .

+122
Dec 03
source share

You can use the :nth-child selector for this

 li:nth-child(3n) { /* your rules here */ } 
+7
Dec 03
source share

try it

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

Demo

nth-child browser support

+4
Dec 03
source share

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

+1
Dec 04 '12 at 4:12
source share



All Articles