Search code examples
csshtml-tableprogress

Progress bar as background of table


I have an HTML table showing a list of person. For each row, I would like to have a different progressbar-like background. Something like

<table>
  <tr class="progress-full">...</tr>
  <tr class="progress-half">...</tr>
  <tr class="progress-quarter">...</tr>
</table>

With the whole background of the first row in color, half of the secord and 1/4 of the last one (with classes or using directly the percentage in CSS).

I tried using a background with a width (like here) but I didn't succeed. Can I enclose a div inside a tr ? When I inspect the html code (eg: with chrome) the div seems outside of the table.

<table style="width: 300px;">
      <tr style="width: 75%; background: rgb(128, 177, 133);">
        <div style="width: 300px;">...</div>
      </tr>
      <tr style="width: 50%; background: rgb(128, 177, 133);">
        <div style="width: 300px;">...</div>
      </tr>
</table>

Or maybe another method ?


Solution

  • You could avoid adding any extra markup to your table if you use CSS ::before or ::after pseudo-elements. You can give each table row a transparent background, and give the pseudo-element the width you want.

    Here's a jsfiddle example.

    enter image description here

    HTML:

    <table>
        <tr class="progress-full">
            <td>Row 1 Col 1</td>
        </tr>
        <tr class="progress-quarter">
            <td>Row 2 Col 1</td>
        </tr>
        <tr class="progress-half">
            <td>Row 3 Col 1</td>
        </tr>
    </table>
    

    CSS:

    td { padding: 10px; }
    
    tr.progress-full td:first-child,
    tr.progress-half td:first-child,
    tr.progress-quarter td:first-child {
        position: relative;
    }
    tr.progress-full td:first-child::before,
    tr.progress-half td:first-child::before,
    tr.progress-quarter td:first-child::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        width: 0;
        height: 100%;
        background-color: red;
        z-index: -1;
    }
    
    tr.progress-full td:first-child::before {
        width: 100%;
    }
    tr.progress-half td:first-child::before {
        width: 50%;
    }
    tr.progress-quarter td:first-child::before {
        width: 25%;
    }
    

    This CSS could be slimmed down, depending on how variable the table structure is. I applied the styles onto the first td inside each tr. If you need the progress bar to stretch across multiple tds, use a width of greater than 100%.