CASE: HTML table using colspan

When creating an HTML table, sometimes it occurs a column needs to span 3 columns of a row below or above it. In this way, it’s very similar to the merge functionality in excel. In HTML it’s possible to do this in the same table (whereas in markdown tables you would need to create a new table to accomplish this).

The attribute for this is colspan and it can be used on both <td> and <th> tags. The attribute needs to be applied to the cell that you want to merge, defining the number of columns you want it to take. The syntax is as follows :

<th class="usr-line-bottom" colspan="2">cell content</th>

Input:

{% capture all_borders_class %}usr-line-bottom usr-line-top usr-line-left usr-line-right{% endcapture %}

<table class="usr-width-100">
  <thead>
    <tr>
      <th class="{{ all_borders_class }} usr-align-center" colspan="2">**Income**</th>
      <th class="{{ all_borders_class }} usr-align-center" colspan="2">**Expenses**</th>
    </tr>
    <tr>
      <th class="usr-width-25 {{ all_borders_class }}">**Current year**</th>
      <th class="usr-width-25 {{ all_borders_class }}">**Previous year**</th>
      <th class="usr-width-25 {{ all_borders_class }}">**Current year**</th>
      <th class="usr-width-25 {{ all_borders_class }}">**Previous year**</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="{{ all_borders_class }}">£ 2,000</td>
      <td class="{{ all_borders_class }}">£ 3,000</td>
      <td class="{{ all_borders_class }}">£ 4,000</td>
      <td class="{{ all_borders_class }}">£ 5,000</td>
    </tr>
  </tbody>
</table>

Output:

Colspan is also useful when our table has empty rows and we don’t want to repeat the many times.

Input:

      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>

Colspan allows us to create one and set the total number of columns in the table as the colspan value which is much more efficient. The example below also makes use of the class usr-bordered, which is the HTML equivalent of # tables in markdown.

Input:

<table class="usr-bordered">
  <thead>
    <tr>
      <th>Header 1</th>
      <th>Header 2</th>
      <th>Header 3</th>
      <th>Header 4</th>
      <th>Header 5</th>
      <th>Header 6</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Row 1</td>
      <td>Row 1</td>
      <td>Row 1</td>
      <td>Row 1</td>
      <td>Row 1</td>
      <td>Row 1</td>
    </tr>
    <tr>
      <td colspan="6"></td>
    </tr>
  </tbody>
</table>

Output:
image (3)