【问题标题】:CSS - Hide first <tr> with ClassCSS - 用 Class 隐藏第一个 <tr>
【发布时间】:2019-12-05 18:37:43
【问题描述】:
我需要隐藏第一个 tr.snip 行
为什么这个 CSS 不起作用?
.table tr.snip:first-child {
display:none!important;
}
html
<table>
<tbody>
<tr>...</tr>
<tr class="snip">...</tr>
<tr class="snip">...</tr>
</tbody>
</table>
【问题讨论】:
标签:
css
class
html-table
row
【解决方案1】:
当您说.snip:first-child 时,您正在寻找既具有snip 类又是其父级的第一个子级的东西。在您的表格中,snip 类的第一行是第三个孩子,因此选择器不起作用。
在选择器级别 4 出现之前,您无法以您尝试的方式直接选择事物,因此目前您最好的选择是尝试将兄弟选择器(+ 和 ~)与伪选择器。你具体做什么取决于你的用例有多复杂。
您的示例最简单的解决方案是:
tr + tr.snip {
display: none;
}
如有必要,您还可以尝试以下方法:
tr:not(.snip) + tr.snip {
display: none;
}
或者你可以反过来做:
tr.snip {
display: none;
}
tr.snip + tr.snip {
display: table-cell;
}
或者(如果这样更合适的话):
tr.snip {
display: none;
}
tr.snip ~ tr {
display: table-cell;
}
【解决方案2】:
因为您试图选择一个tr.snip,它是ALSO其父级的first child。您要隐藏的 tr.snip 是其父级的第二个子级,因此它与 CSS 选择器不匹配。
另外,不要忘记将您的内容放入td,如下所示:
<tr class="snip"><td>...</td></tr>