Computer scienceFrontendHTMLBasic TagsTables

Tables: Merging cells

3 minutes read

In the previous topic you've practiced creating tables, but they were quite simple and similar. Today you will learn how to merge cells to create tables for a variety of situations when you need to group data.

Two ways to merge cells

You can merge cells in your table both vertically and horizontally. There are two attributes for this:

  • colspan allows you to merge cells horizontally, the number of cells to be merged is given as a value;

  • rowspan allows you to merge cells vertically, the number of cells to be merged is given as a value.

The value of either attribute has to be a positive integer. It specifies the number of columns or rows that the cell fills.

Here is a standard HTML table that shows types of soup and their prices from the previous topic.

<table border="1">
  <tr>
    <th>Main dishes</th>
    <th>Price</th>
  </tr>
  <tr>
    <td>Tomato soup</td>
    <td>$3.95</td>
  </tr>
  <tr>
    <td>French onion soup</td>
    <td>$4.49</td>
  </tr>
</table>

The browser will render it as follows:

Three rows by two columns table

We will use this table to demonstrate both colspan and rowspan tags.

Merging cells horizontally

Let's try to merge the cells horizontally:

<table border="1">
  <tr>
    <th>Main dishes</th>
    <th>Price</th>
  </tr>
  <tr>
    <td colspan="2">Tomato soup</td>
    <td>$3.95</td>
  </tr>
  <tr>
    <td>French onion soup</td>
    <td>$4.49</td>
  </tr>
</table>

In the above example, one of the cells is shifted to the right.

Table with the cell outside

To correct this situation and make the table more pleasant to look at, you may remove an extra cell:

<table border="1">
  <tr>
    <th>Main dishes</th>
    <th>Price</th>
  </tr>
  <tr>
    <td colspan="2">Tomato soup</td>
  </tr>
  <tr>
    <td>French onion soup</td>
    <td>$4.49</td>
  </tr>
</table>

Table with spanned columns in the second row

Merging cells vertically

The rowspan attribute to merge cells vertically is applied the same way:

<table border="1">
  <tr>
    <th>Main dishes</th>
    <th>Price</th>
  </tr>
  <tr>
    <td rowspan="2">Tomato soup</td>
    <td>$3.95</td>
  </tr>
  <tr>
    <td>French onion soup</td>
    <td>$4.49</td>
  </tr>
</table>

The cell outside the table

The cells of the table have shifted, as with colspan. Let's remove an extra cell to make the table better-looking:

<table border="1">
  <tr>
    <th>Main dishes</th>
    <th>Price</th>
  </tr>
  <tr>
    <td rowspan="2">Tomato soup</td>
    <td>$3.95</td>
  </tr>
  <tr>
    <td>$4.49</td>
  </tr>
</table>

The spanned row in the first column of the table

So in this topic we've learned how to merge attributes in the tables using colspan and rowspan. Use them when you need to create non-standard tables with one cell for several columns or rows.

134 learners liked this piece of theory. 6 didn't like it. What about you?
Report a typo