CSS striped color div

I'm trying to use the zebra strip for my divs on my website, it sounds simple enough, however, I found that when I added the title between the lines of my divs, it seemed to count the title in an odd / clear style

HTML

<div class="container"> <h3>Title</h3> <div class="row">Content</div> <div class="row">Content</div> <h3>Title</h3> <div class="row">Content</div> <div class="row">Content</div> <div class="row">Content</div> <h3>Title</h3> <div class="row">Content</div> <div class="row">Content</div> <div class="row">Content</div> <div class="row">Content</div> </div> 

CSS

 .container { width:600px; margin:0 auto; } .row { line-height:24pt; border: solid 1px black; } .row:nth-child(odd) { background: #e0e0e0; } h3 { line-height:36pt; font-weight:bold; color:blue; } 

fiddle

I would have thought that the code already in the fiddle would basically ignore the title and wrap the bar, but it seems like it treats the title as a child

+57
html css zebra-striping
Feb 21 '13 at 14:19
source share
3 answers

Do not use nth-child , use nth-of-type

 div.container > div:nth-of-type(odd) { background: #e0e0e0; } 

 .container { width: 600px; margin: 0 auto; } .row { line-height: 24pt; border: solid 1px black; } div.container>div:nth-of-type(odd) { background: #e0e0e0; } h3 { line-height: 36pt; font-weight: bold; color: blue; } 
 <div class="container"> <h3>Title</h3> <div class="row">Content</div> <div class="row">Content</div> <div class="row">Content</div> <div class="row">Content</div> <h3>Title</h3> <div class="row">Content</div> <div class="row">Content</div> <h3>Title</h3> <div class="row">Content</div> <div class="row">Content</div> <div class="row">Content</div> <div class="row">Content</div> <div class="row">Content</div> <h3>Title</h3> <div class="row">Content</div> <div class="row">Content</div> <div class="row">Content</div> <div class="row">Content</div> </div> 
+99
Feb 21 '13 at 14:24
source share

You probably want to combine the type, not the child.

Usage: nth-of-type e.g.

 .row:nth-of-type(odd) { background: #e0e0e0; } 
+7
Feb 21 '13 at 14:25
source share

The simplest solution is, of course, to simply wrap the elements you want striped.

Updated jsFiddle .

HTML

 <div class="container"> <h3>Title</h3> <div class="zebra"> <div class="row">Content</div> <div class="row">Content</div> </div> <h3>Title</h3> <div class="zebra"> <div class="row">Content</div> <div class="row">Content</div> <div class="row">Content</div> </div> <h3>Title</h3> <div class="zebra"> <div class="row">Content</div> <div class="row">Content</div> <div class="row">Content</div> <div class="row">Content</div> </div> </div> 

CSS

 .row:nth-child(odd) {background: #e0e0e0;} 

Remember also that if browser support is important to you, you may want to create additional classes for the server side of the zebra.

+5
Feb 21 '13 at 14:23
source share



All Articles