tr:n-child(偶数)帮助。如何申请一堂课?

时间:2009-10-15 01:07:40

标签: css css-selectors css-tables

我对CSS不是很好,我需要一些帮助。

我有一张桌子,我希望每隔一行都是灰色的,交替的行是白色的。但我只希望它发生在一个特定的桌子上。

我在CSS中添加了一些代码:

tr:nth-child(even) {  
background: #CCC;  
}  

tr:nth-child(odd) {  
background: #FFF;  
}  

但问题是它会影响我网站上的每个表格。 我没有找到任何只适用于某个类的例子。那可能吗?我希望它仅适用于:

table.dashboardtable  

3 个答案:

答案 0 :(得分:11)

像往常一样使用CSS后代组合子(并置):

table.dashboardtable tr:nth-child(even)
table.dashboardtable tr:nth-child(odd)

答案 1 :(得分:2)

nth-childnth-of-type接受oddeven以及类似an+b的公式,其中ab是常数。

通常你想使用nth-of-type,它只适用于你指定的类型。这将遗漏其他因素。如果您希望每个偶数tr都具有该背景颜色,请尝试:

tr:nth-of-type(2n){
  background: #CCC;
}

tr:nth-of-type(2n+1){
  background: #FFF;
}

More info on CSS Selectors

答案 2 :(得分:2)

希望这有意义。

<!DOCTYPE html>

<html>
  <head>
    <style type="text/css">
      #customers tr:nth-child(even){
        background-color:white;
      }
      #customers tr:nth-child(odd){
        background-color:Lavender;
      }
    </style>
  </head>

  <body>
    <p>In your markup define your table:</p>
      <table id="customers"></table>
  </body>
</html>
相关问题