首页 > 解决方案 > 使用CSS在第二个表中选择第一个表的第一行和第二个表中具有相同类的最后一行

问题描述

我有两个表,如下所示,具有相同的类。我的要求是使用 CSS 选择第一个表的第一行和第二个表的最后一行。

<table class='mx-table'>
 <tr class="mx-active-week">
 <tr class="mx-active-week">
</table>
<table class='mx-table'>
 <tr class="mx-active-week">
 <tr class="mx-active-week">
</table>

我试过了,.mx-active-week:nth-child(1)但它给了我第二张桌子的第一行。我不想使用表类.mx-table:nth-child(1) .mx-active-week:nth-child(1)来获取第一个表的第一行。

是否可以仅用mx-active-week于此目的?

请帮忙。

谢谢,乔蒂

标签: htmlcss

解决方案


如果您不想使用:nth-child,则可以使用其他伪类,例如:first-of-type:last-of-type来选择第一个和最后一个<table>元素。然后用于:first-child定位第一个表<tr>:last-child定位第二个表的最后一个<tr>

using:first-of-type选择一组兄弟元素中的第一个元素,其中:last-of-type选择一组兄弟元素中的最后一个元素。在这个例子中,这两个<table>是兄弟元素。

/* can remove this table styling, used for better visual */
table {
  margin: .5rem 0;
  border: .1rem solid #333;
}

.mx-table:first-of-type .mx-active-week:first-child {
  color: #f06;
}

.mx-table:last-of-type .mx-active-week:last-child {
  color: blue;
}
<table class='mx-table'>
 <tr class="mx-active-week">
  <td>First row of first table</td>
 </tr>
 <tr class="mx-active-week">
  <td>Last row</td>
 </tr>
</table>
<table class='mx-table'>
 <tr class="mx-active-week">
  <td>First row</td>
 </tr>
 <tr class="mx-active-week">
  <td>Last row of second table</td>
 </tr>
</table>

如果您只想使用.mx-active-week选择第一行或最后一行。你可以只使用.mx-active-week:first-of-typeor .mx-active-week:last-of-type。使用:first-childand:last-child也可以以相同的方式在一组兄弟元素中选择第一个和最后一个<tr>元素。就像您在评论中提到的那样,可能是.mx-active-week第一个表中不存在该类,所以我在下面展示了这一点。

/* can remove this table styling, used for better visual */
table {
  margin: .5rem 0;
  border: .1rem solid #333;
}

.mx-active-week:first-of-type {
  color: #f06;
}

.mx-active-week:last-of-type {
  color: blue;
}
<table class='mx-table'>
 <tr>
  <td>First row of first table</td>
 </tr>
 <tr>
  <td>Last row</td>
 </tr>
</table>
<table class='mx-table'>
 <tr class="mx-active-week">
  <td>First row</td>
 </tr>
 <tr class="mx-active-week">
  <td>Second row</td>
 </tr>
 <tr class="mx-active-week">
  <td>Last row of second table</td>
 </tr>
</table>


推荐阅读