16

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!

ekad
  • 13,718
  • 26
  • 42
  • 44
Allen Hundley
  • 191
  • 1
  • 1
  • 4

2 Answers2

4

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>
SalDevOps
  • 394
  • 1
  • 9
1

You can add the html col tag to group the columns td.

.col-group-1 {
  background-color: yellow;
 }

.col-group-2 {
  background-color: silver;
 }
<table>
  <colgroup>
    <col class="col-group-1">
    <col span="2" class="col-group-2">
  </colgroup>
  <tr>
    <th>Name</th>
    <th>City</th>
    <th>Phone</th>
  </tr>
  <tr>
    <td>Mary</td>
    <td>New york</td>
    <td>987654321</td>
  </tr>
  <tr>
    <td>Magdalena</td>
    <td>Los Angeles</td>
    <td>123456789</td>
  </tr>
</table>

</body>
</html>

Please check out the html col tag

and how to use them with css styling

Lee Loback
  • 19
  • 2