使用 CSS 计数器增量时如何排除表中的第一行和最后一行

问题描述

我正在使用下面的代码对表格中的行进行编号。但我需要排除第一行是头部,最后一行只是最后一行。头部的排除工作正常。我试过这个:

table#thisNet {
    counter-reset: netLogCounter;
}

table#thisNet td:first-child::before {
    counter-increment: netLogCounter;
}

table#thisNet tr:not(thead) tr:not(:last-child)  td:first-child::before {
    content: counter(netLogCounter);
}

但是这让每个空白......根本没有数字。

我也试过了:

table#thisNet tr:not(thead,last-child::before)  td:first-child::before {
    content: counter(netLogCounter);
}

但又没有快乐。 只有这样它才有效,但最后一行是数字。

table#thisNet tr:not(thead) td:first-child::before {
    content: counter(netLogCounter);
}

是否可以将第一行和最后一行都排除在计数器增量之外,如果可以,如何?

解决方法

您可以为表创建一个计数器,并使用如下选择器在不是第一行 (:first-child) 和最后一行 (:last-child) 的每一行中递增它:

table#thisNet tr:not(:first-child):not(:last-child) {
  counter-increment: netLogCounter;
}

在这里你可以看到一个演示:

table#thisNet {
  counter-reset: netLogCounter 0;
}

table#thisNet tr:not(:first-child):not(:last-child) {
  counter-increment: netLogCounter;
}

table#thisNet tr:not(:first-child):not(:last-child) td:first-child::before {
  content: counter(netLogCounter); 
}
<table id="thisNet">
  <tr><td>ID</td><td>Value</td></tr>
  <tr><td></td><td>3</td></tr>
  <tr><td></td><td>2</td></tr>
  <tr><td></td><td>4</td></tr>
  <tr><td></td><td>6</td></tr>
  <tr><td>TOTAL</td><td>15</td></tr>
</table>

理想情况下,表格的结构如下:

<table>
  <thead>...</thead>
  <tbody>...</tbody>
  <tfoot>...</tfoot>
</table>

然后您只想计算 tbody 内的行数,以简化选择器的逻辑:

table#thisNet tbody tr {
  counter-increment: numRows;
}

做一些类似这个演示的事情:

在这里你可以看到一个演示:

table#thisNet {
  counter-reset: netLogCounter 0;
}

table#thisNet tbody tr {
  counter-increment: netLogCounter;
}

table#thisNet tbody tr td:first-child::before {
  content: counter(netLogCounter); 
}
<table id="thisNet">
  <thead>
    <tr><th>ID</th><th>Value</th></tr>
  </thead>
  <tbody>
    <tr><td></td><td>3</td></tr>
    <tr><td></td><td>2</td></tr>
    <tr><td></td><td>4</td></tr>
    <tr><td></td><td>6</td></tr>
  </tbody>
  <tfoot>
    <tr><td>TOTAL</td><td>15</td></tr>
  </tfoot>
</table>