A way to group table cells together in html?

Allen Hundley picture Allen Hundley · Mar 23, 2012 · Viewed 17.6k times · Source

So it is pretty straight forward. I need a way to group cells together. Like a <div> or a <span> but none of them worked. <tbody> seemed like a good solution but it only works for table rows. Help!

Answer

SalDevOps picture SalDevOps · Jun 25, 2019

If you're looking for a way to merge 2 o more cells in a row into one single cell, along with other "regular" cells (as you would do in a google|excel spreadsheet) in a way similar to this:

Merged Cells inside a table with other regular rows

then you can use the colspan attribute for td elements, indicating how many cells are you merging:

<tr>
  <td colspan=2> Merged Cell occupying 2 columns </td>
</tr>
<tr>
  <td> Regular cell </td>
  <td> Another cell in same row </td>
</tr>

Additionally, you can use the td[colspan] selector in css (combined with any parent selector of your choice) to refer to these merged cells.

Here's a working example:

/* Style for cells with any colspan attribute */
td[colspan] {
  text-align: center;
}

/* No extra space between cells */
table {
  border-collapse: collapse;
}

th, td {
  border: 1px solid gray;
  margin: 0;
  padding: 3px 10px;
  text-align: right;
}
<table>
  <tr>
    <th>Day</th>
    <th>Invoice</th>
    <th>Total</th>
  </tr>
  <tr>
    <!-- this cell will occupy 3 columns -->
    <td colspan=3>January</td>
  </tr>
  <tr>
    <td>2</td>
    <td>0348</td>
    <td>248.35</td>
  </tr>
  <tr>
    <td>7</td>
    <td>0349</td>
    <td>126.14</td>
  </tr>
  <tr>
    <td>18</td>
    <td>0350</td>
    <td>821.99</td>
  </tr>
  <tr>
    <td colspan=3>February</td>
  </tr>
  <tr>
    <td>27</td>
    <td>0351</td>
    <td>643.50</td>
  </tr> 
</table>