【问题标题】:tr:nth-child(even) help. how to apply to one class?tr:nth-child(even) 帮助。如何申请一个班级?
【发布时间】:2017-01-14 18:40:43
【问题描述】:

我不太擅长 CSS,我需要一些帮助。

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

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

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

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

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

table.dashboardtable  

【问题讨论】:

    标签: css css-selectors css-tables


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!这正是我所需要的。出于某种原因,我在dashboardtable 和tr 之间加了一个点。多么愚蠢的错误。大声笑。
    • 我想使用table.dashboardtable > tr:nth-child(子选择器>)可能是个好主意,这样如果您有嵌套表,它就不会意外地应用于这些表。
    【解决方案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

    【讨论】:

    • ive 只用 ff3 试过,但奇怪甚至对我有用。生病切换到公式,以防万一有浏览器不支持的话。谢谢!
    【解决方案3】:

    希望这是有道理的。

    <!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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      • 1970-01-01
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多