0

I have a table similar to this example

<tr class="line">...</tr>
<tr class="line">...</tr>
<tr class="line">...</tr>
<tr class="sum-line" id="i-know-this-one">...</tr>
<tr class="sum-line">...</tr>
<tr class="sum-line">...</tr>

With css (no jquery), how do I select the last .line? that is, the last tr before the #i-know-this-one.

Keep in mind that amount of rows before after #i-know-this-one will vary in my context, so we cannot simply count nth-child from top or bottom of the table

Eldamir
  • 9,888
  • 6
  • 52
  • 73

1 Answers1

0

If you use php or other language to output your table, then add a class or id to the last tr.line. And then apply styles to it.

Or use this, if it's applicable for your problem.

tr:nth-last-child(3) {
  background-color: lime;
}
<table>
  <tr class="line"><td>...</td></tr>
  <tr class="line"><td>...</td></tr>
  <tr class="line"><td>...</td></tr>
  <tr class="sum-line" id="i-know-this-one"><td>...</td></tr>
  <tr class="sum-line"><td>...</td></tr>
  <tr class="sum-line"><td>...</td></tr>
</table>

Or another way: Use tbody for .line and tfoot for .sum-line. There will not be any problems then.

   tbody tr:last-child {
      background-color: lime;
    }
    <table>
      <tbody>
        <tr class="line"><td>...</td></tr>
        <tr class="line"><td>...</td></tr>
        <tr class="line"><td>...</td></tr>
      </tbody>
      <tfoot>
        <tr class="sum-line" id="i-know-this-one"><td>...</td></tr>
        <tr class="sum-line"><td>...</td></tr>
        <tr class="sum-line"><td>...</td></tr>
      </tfoot>
    </table>
murrometz
  • 904
  • 1
  • 8
  • 12