Why does every row have a red background when I’m using nth-child(odd)?
<div id="ClientTable">
<div class="ClientTableHeaderRow"><span class="ClientTableHeaderColumn">Full Name</span></div>
<div class="ClientTableRow"><span class="ClientName">Umpa Beeson</span></div>
<div class="ClientTableRow"><span class="ClientName">Umpa Beeson</span></div>
<div class="ClientTableRow"><span class="ClientName">Umpa Beeson</span></div>
<div class="ClientTableRow"><span class="ClientName">Umpa Beeson</span></div>
</div>
#ClientTable {position: relative;
display: table;
margin-top: 20px;
width: 100%;}
#ClientTable:nth-child(odd) {background-color:#FF0000;}
.ClientTableHeaderRow, .ClientTableRow {display: table-row; }
.ClientTableHeaderRow {font-weight: bold;}
.ClientTableHeaderRow span, .ClientTableRow span {display: table-cell;}
The expected result is every other row to be red. Instead, as you can see, every row is red.
P.S. Umpa is my cat.
You should be setting
ClientTableRowclass, like so:Demo: http://jsfiddle.net/gMR2K/4/
EDIT
As also explained by animuson, you need to apply the
:nth-childselector to the element itself, not the parent. The name of the selector can lead one to think it will apply the styling to the children of the selected element, when actually the style is applied to n-th child of the selected element, across the whole document.Also, if you’re worried about browser compatibility you can also do this with JavaScript. Here’s an example using jQuery.
Demo: http://jsfiddle.net/gMR2K/10/
As stated here by BoltClock: jQuery “polyfills the :nth-child() selector for older browsers anyway.”