Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do CSS nth-child in span tags?

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>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                </div>
            </td>
            <td>
                <div>
                    <span>TOTAL SWAPS:</span><br />
                    <span id="algTotalSwaps">50</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                </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/

like image 817
Universal Grasp Avatar asked Dec 26 '22 05:12

Universal Grasp


2 Answers

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/

like image 80
Vangel Tzo Avatar answered Dec 28 '22 07:12

Vangel Tzo


: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
like image 42
Salman A Avatar answered Dec 28 '22 08:12

Salman A