user3052619
user3052619

Reputation: 29

Change only pair or unpair divs from a container

I'm trying to make pair or unpair divs from a container to have a different background. For example the first one has a red background, the second blue, the third red the fourth blue and so...

This is my code:

<div>...</div>
<div>...</div>
<div>...</div>
<div>...</div>
<div>...</div>
<div>...</div>

div { width:50px; height:50px; background:red; }

I really don't know how to achieve this. I don't know if I need only css or jquery too.

Thank you.

Upvotes: 0

Views: 277

Answers (2)

Ashisha Nautiyal
Ashisha Nautiyal

Reputation: 1397

use pseudo selector nth-child of CSS property . By using this u can select odd even node

div:nth-child(odd) { background-color: #FF0000; }
div:nth-child(even) { background-color: #0000FF; }

Upvotes: 0

John S
John S

Reputation: 21492

You can do this with just CSS by using the :nth-child selector:

div { width: 50px; height: 50px; }
div:nth-child(odd) { background-color: red; }
div:nth-child(even) { background-color: blue; }

jsfiddle

Upvotes: 1

Related Questions