Apparently the nth-child pseudo is working well with tds or trs in a table. but what about span tags?
HTML:
<div id="refals_wr" style="font: normal 14px Verdana, Geneva, sans-serif; border-top: 2px dashed #CCC;">
<table width="100%" border="0" cellspacing="5" cellpadding="5">
<tr>
<td>
<div>
<span>NAME OF SORTING ALGORITHM:</span><br />
<span id="algName">Bubble Sort</span>
</div>
</td>
<td>
<div>
<span>TOTAL SWAPS:</span><br />
<span id="algTotalSwaps">50</span>
</div>
</td>
<td>
<div>
<span>SWAP COUNT:</span><br />
<span id="algSwapCount">8</span>
</div>
</td>
</tr>
</table>
</div>
CSS:
#refals_wr span:nth-child(odd) { color: green; }
#refals_wr span:nth-child(even) { color: orange; }
Does not give desired result, everything is Green! Also, the last span (the one under SWAP COUNT containing the number "8") should not be affected in the coloring.
Is there a better way?
Fiddle: http://jsfiddle.net/xzdv5csp/
You should use nth-of-type
#refals_wr span:nth-of-type(odd){
color:green;}
#refals_wr span:nth-of-type(even){
color:orange;}
An example: http://jsfiddle.net/xzdv5csp/1/
:nth-child
matches if the element is the specified child of its parent. The <br>
element inside the div is causing the odd and even part of your selectors to fail since it makes both spans odd children (1st and 3rd) of its parent.
The following alternatives should work, even in lame browsers:
#refals_wr span { color: green; }
#refals_wr span[id] { color: orange; }
/* Or */
#refals_wr span { color: orange; }
#refals_wr span:first-child { color: green; }
Updated Demo
Now that you mention that the last span in last cell must be treated differently, there are couple of ways to do it but they all involve targeting or excluding the last td
element. Here is one example that uses :not()
:
#refals_wr span { color: green; }
#refals_wr td:not(:last-child) span[id] { color: orange; }
/* Or */
#refals_wr2 span { color: green; }
#refals_wr2 td:not(:last-child) span:last-child { color: orange; }
Updated Demo
If you want to avoid :not()
due to browser support then you could use for example:
td:last-child
td:first-child, td:first-child + td
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With