Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styling every 3rd item of a list using CSS? [duplicate]

Tags:

html

css

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?

like image 344
Gezzamondo Avatar asked Dec 03 '12 21:12

Gezzamondo


People also ask

How would you style every third item in a list?

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() is compatible in Chrome, Firefox, and IE9+.

How do I target every third element in CSS?

formula (an + b)nth-child(3n+1) would apply to every third element starting from the first one.

Can I select multiple elements at once with CSS?

When you group CSS selectors, you apply the same styles to several different elements without repeating the styles in your stylesheet. Instead of having two, three, or more CSS rules that do the same thing (set the color of something to red, for example), you use a single CSS rule that accomplishes the same thing.


2 Answers

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.

like image 52
dsgriffin Avatar answered Oct 07 '22 03:10

dsgriffin


You can use the :nth-child selector for that

li:nth-child(3n) {  /* your rules here */ } 
like image 43
Sirko Avatar answered Oct 07 '22 03:10

Sirko