Home > database >  Making las child of a table the same color as the table element above it
Making las child of a table the same color as the table element above it

Time:04-16

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.

CodePudding user response:

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;
}

CodePudding user response:

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 >
  <table >
    <tbody>
      <tr><td>blah blah blah</td></tr>
      <tr><td>blah blah blah</td></tr>
    </tbody>
  </table>
  <table >
    <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 >
    <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>

  • Related