'Making last child of a table the same color as the table element above it

I have a table and in the css I'm using nth-child to make the background colors different:

.className tr:nth-child(even) {
    background: #F0F0F0;
}

.className tr:nth-child(odd) {
    background: #FFF;
}

The table is created dynamically so there is no way to know how many rows there will be.

The design needs the last child of the table to match the background color of the child above it.

This is being built in TWIG.



Solution 1:[1]

You can test both for last child and for odd or even.

tr:last-child:nth-child(odd) td{
  background: #f0f0f0;
}
tr:last-child:nth-child(even) td{
  background: #fff;
}

Solution 2:[2]

I'm not aware of a way to inherit a property value outside the scope of a parent-child scenario (eg; cascading style sheets). However if you're up for some javascript you can do it regardless whether it ends with odd or even. Example below.

const tables = document.getElementsByClassName('className');

for (let i = 0, x = tables.length; i < x; i++) {
  const rowCount = tables[i].rows.length;
  
  tables[i].rows[rowCount-1].style.backgroundColor = 
  window.getComputedStyle(tables[i].rows[rowCount-2]).backgroundColor;

}
.className tr:nth-child(even) {
  background-color: red;
}

.className tr:nth-child(odd) {
  background-color: blue;
}

.examples {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  color: #fff;
  background-color: #212121;
}

.examples table {
  margin: 3rem 1rem;
}
<section class="examples">
  <table class="className">
    <tbody>
      <tr><td>blah blah blah</td></tr>
      <tr><td>blah blah blah</td></tr>
    </tbody>
  </table>
  <table class="className">
    <tbody>
      <tr><td>blah blah blah</td></tr>
      <tr><td>blah blah blah</td></tr>
      <tr><td>blah blah blah</td></tr>
      <tr><td>blah blah blah</td></tr>
      <tr><td>blah blah blah</td></tr>
      <tr><td>blah blah blah</td></tr>
    </tbody>
  </table>
  <table class="className">
    <tbody>
      <tr><td>blah blah blah</td></tr>
      <tr><td>blah blah blah</td></tr>
      <tr><td>blah blah blah</td></tr>
      <tr><td>blah blah blah</td></tr>
      <tr><td>blah blah blah</td></tr>
    </tbody>
  </table>
</section>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 A Haworth
Solution 2