Tutorial :How to get alternate colors div with pure css and with IE 7 support?


This is HTML.

<div class="container">              <div> background of this i need in white </div>              <div> background of this i need in red </div>              <div> background of this i need in white </div>              <div> background of this i need in red </div>          </div>  

I want to select alternate div without adding class or id .

Is it possible with CSS only (no Javascript) with IE 7 support


IE7 doesn't support the selector you would require, which is :nth-child().

Generally you would use

.container div:nth-child(even) {       background: red;  }  

IE7 does not support it, unfortunately.

You will need to use JavaScript, or add a class to every odd or even row (perhaps using a server side language).


can't we select every second div inside <div class="container"> [with the CSS2 selectors introduced by IE7]?

Well kind of, with the adjacency selector:

.container div { background: white; }  .container div+div { background: red; }  .container div+div+div { background: white; }  .container div+div+div+div { background: red; }  

But that means writing out a rule (of increasingly unwieldy length) for each child. The above covers the example markup with four children, so it's manageable for short, fixed-number-of-children elements, but impractical for elements with a large or unlimited number of children.


This cannot be done.


Use in-line style tags, like, the following works in IE 7 not tested for others.

<div style="background-color:#ffff00" > Hello YOU div</div>  


div:nth-child(odd) { background-color:#ffffff; }  div:nth-child(even) { background-color:#ff0000; }  

but i don't know (and can't test) if this works in IE7 - if not, you'll have to use different classes for the divs.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »