Search code examples
htmlcsshtml-tablebackgroundbackground-color

Is it possible to highlight part of a colspan column in CSS?


I have an HTML table that looks something like this:

I've set the colors using colgroups.

  <colgroup>
    <col style="background-color:lightgrey">
    <col style="background-color:white">
    <col style="background-color:lightgrey">
  </colgroup>

What I'd like is to have a striped table, where columns alternate colors and for this to take effect in the colspan rows. I.e. I want something like this:

What's the easiest way for me to achieve this?

Thanks

JSfiddle: https://jsfiddle.net/kq1hnmuw/7/


Solution

  • Not sure if this would work for your actual table, but you could maybe try something like this:

    table {
      overflow:hidden;
    }
    tr:first-child > th {
      position:relative;
    }
    tr:first-child > th::before {
      content: '';
      position:absolute;
      top:0;
      left:0;
      right:0;
      bottom:-1000px; /* i.e. minus of any value that is greater than the height of your table */
      background-color:lightgrey;
      z-index:-1;
    }
    tr:first-child > th:nth-child(2)::before {
      background-color:white;
    }
    <!DOCTYPE html>
    <html>
    <head>
    
    </head>
    <body>
    
    <table border>
      <tr>
        <th>Month</th>
        <th>Savings</th>
        <th>Name</th>
      </tr>
      <tr>
        <td>January</td>
        <td>$100</td>
        <td>Jack</td>
      </tr>
      <tr>
        <td>February</td>
        <td>$80</td>
        <td>Andrew</td>
      </tr>
      <tr>
        <td colspan="3">Sum: $180</td>
      </tr>
    </table>
     
    </body>
    </html>