2014-08-28 24 views
2

显然,第n个孩子的伪和表格中的tds或trs很好地协作。但span标签呢?如何在span标签中做CSS nth-child?

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; } 

不放弃希望的结果,一切都是绿色的!另外,最后一个跨度(包含数字“8”的SWAP COUNT下的一个)应该在着色中受到影响而不是

有没有更好的方法?

小提琴:http://jsfiddle.net/xzdv5csp/

+0

给定这个标记,第一个孩子是'span',第二个孩子是'br',最后一个'span'是每个'div'的第三个孩子。这解释了这种行为。正如srekoble所建议的那样,“n型”只涉及一种类型的元素(即这里称为“跨度”)。 – 2014-08-28 07:11:24

回答

4

您应该使用nth-of-type

#refals_wr span:nth-of-type(odd){ 
    color:green;} 

#refals_wr span:nth-of-type(even){ 
    color:orange;} 

一个例子:http://jsfiddle.net/xzdv5csp/1/

+0

工作得很好,浏览器的友好程度是多少?任何想法? – 2014-08-28 06:55:19

+0

@UniversalGrasp你可以在这里检查支持http:// caniuse。com /#feat = css-sel3 – 2014-08-28 07:07:40

+0

浏览器支持与'nth-child'相同:http://caniuse.com/#search=nth-of-type – 2014-08-28 07:08:41

2

TRY - DEMO

#refals_wr span { 
    color:orange; 
} 

#refals_wr span:nth-child(1) { 
    color:green; 
} 
+0

whats the(3n + 1)你可以解释??? ...是否与所有浏览器兼容? – 2014-08-28 06:53:18

+0

它适用于我... – Anonymous 2014-08-28 06:55:07

+0

什么是(3n + 1)? – 2014-08-28 06:56:35

2

:nth-child如果元素是其父项的指定子项,则匹配。 div内的<br>元素会导致选择器的奇数和偶数部分失败,因为它使得它们跨越父代的奇数子代(第1和第3)。

有以下两个选项应该工作,甚至在跛脚的浏览器:

#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


既然你提到,在最后一个单元格的最后一个跨度必须区别对待,有几个方法来做到这一点,但他们都涉及针对或排除最后td元素。下面是一个使用: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

如果你想避免:not()由于浏览器的支持,那么你可以使用例如:

  • td:last-child
  • td:first-child, td:first-child + td