【问题标题】:How to find a first td in a tr using tr class name in CSS? [duplicate]如何在 CSS 中使用 tr 类名在 tr 中找到第一个 td? [复制]
【发布时间】:2015-03-29 14:27:34
【问题描述】:

在我的应用程序中,我有一个超过 7 个 tr 和 3 个 td 的表。对于特定媒体,我想更改我的 td 的 colspan 之一。为此,我现在使用 tr 的类名向特定的 tr 添加类名,我想找到该 tr 的第一个和最后一个子级。这个怎么做? 不使用任何脚本(jquery/java)。我想只使用 css 来做到这一点。

 <table cellspacing="0" cellpadding="0" border="0" style="border- collapse: collapse; width:100%; table-layout:fixed;">
    <tbody>
    <tr>
    <td>some content</td>
    <td>some content</td>
    <td>some content</td>
    </tr>
   <tr>
    <td>some content</td>
    <td>some content</td>
    <td>some content</td>
    </tr>
     <tr>
    <td>some content</td>
    <td>some content</td>
    <td>some content</td>
    </tr>
    <tr class="media">
    <td>some content</td>
    <td>some content</td>
    <td>some content</td>
     </tr>
      </tbody>
   </table>

【问题讨论】:

  • 在这里你可以看到输出。 ** jsfiddle.net/HardRocks/x05bcust **
  • 哇,有七个答案,其中一半以上的人答错了。这是重复的,但我几乎很想自己发布一个答案,只是为了解释为什么其他一半是错误的,即使它与手头的问题无关。

标签: html css css-selectors


【解决方案1】:

只需执行以下操作即可。

.media td:first-of-type {
  background: red;
  }

.media td:last-of-type {
  background: green;
  }
<table cellspacing="0" cellpadding="0" border="0" style="border- collapse: collapse; width:100%; table-layout:fixed;">
    <tbody>
    <tr>
    <td>some content</td>
    <td>some content</td>
    <td>some content</td>
    </tr>
   <tr>
    <td>some content</td>
    <td>some content</td>
    <td>some content</td>
    </tr>
     <tr>
    <td>some content</td>
    <td>some content</td>
    <td>some content</td>
    </tr>
    <tr class="media">
    <td>some content</td>
    <td>some content</td>
    <td>some content</td>
     </tr>
      </tbody>
   </table>

注意:如果它们的样式相同,您可以将它们添加在一起,如下所示。

 .media td:last-of-type, .media td:first-of-type {
      background: green;
      }

【讨论】:

  • 您仍然需要在逗号后面重复.media 部分。
  • 我已经更正了。谢谢
【解决方案2】:

对于纯 javascript 代码。

document.getElementsByClassName("class-name").childNodes[0]; //first element

document.getElementsByClassName("class-name").childNodes[2]; //last element

对于 CSS:

.media 是特定 tr 的类。如果您对 tr 使用不同的类,那么您可以使用不同的类名重用下面的代码。

  .media td:first-child{
background-color:red;
}

.media td:last-child{
background-color:red;
}

更多增强功能,如果您对不同的 TR 使用不同的类名,例如 media-1、media-2:

tr[class^="media-"] td:first-child{
background-color:red;
}

tr[class^="media-"] td:last-child{
background-color:red;
}

【讨论】:

  • OP 不是在寻找 JS 解决方案。
  • 我很抱歉。没看到那个。将发布 CSS 解决方案。
  • 仍然不正确 - 您的类选择器放错了位置。
【解决方案3】:

你可以这样做:

.media td:first-child,.media td:last-child{
        background-color: red;
    }

如果你想在.media中选择某个td,可以使用

//n is the td you want select. n starts from 1
.media td:nth-child(n) {
  background-color: red;
}

【讨论】:

    【解决方案4】:

    试试这个

    table tr.media td:first-child{}
    
    table tr.media td:last-child{}
    

    【讨论】:

      【解决方案5】:

      在这里……

      table .media:first-child,
      .media:last-child{
          background-color:red;
      }
      

      【讨论】: