html - 使用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
于此目的?
请帮忙。
谢谢,乔蒂
解决方案
如果您不想使用: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-type
or .mx-active-week:last-of-type
。使用:first-child
and: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>
推荐阅读
- linux - Postgresql 的 Crontab 失败,找不到命令
- python - 从嵌套类访问父 graphene.ObjectType 的数据
- angular - 吸气剂没有返回正确的值
- http-headers - Mule 4 - 无法覆盖 HTTP 响应标头的某些值
- typescript - VS Code Prettier - Code Formatter Extension 不适用于使用 Typescript 模板的 Create-React-App
- python-3.x - 烧瓶测试 400 错误页面没有通过,但它正在工作
- javascript - 无法从控制器获取数据到 Vue 组件
- go - 这是什么意思?
- sql - 翻转列和行 SQL
- java - Spring Security 拦截除注释外