HTML Tables

Menu
Menu

Basic table elements <table>, <tr> and <td>

Basic HTML tables are defined using three core tags. The <table> element defines the beginning of the table and </table> the end.  Each row is created with a <tr> element and ended with a </tr>.  Cells within that row are created with the <td> (table data) element and ended with a closing </td>.  It is inside the <td> tags that the actual content of the table is placed.

Therefore to produce a simple 3 column 2 row table the HTML would be as follows:

That would result in a HTML table as follows.

Column 1 Column 2 Column 3
Value 1 Value 2 Value 3

Tables can be created where one cell spans over more than one row, or more than one column. This is achieved through the use of the colspan and rowspan attributes of the <td> element.

For example:

would produce:

Set to colspan 3
Row 2 Cell 1 Row 2 Cell 2 Row 2 Cell 3
Set to rowspan to 2 Row 3 Cell 2 Row 3 Cell 3
Row 4 Cell 2 Row 4 Cell 3

Semantic Rich Tables with th, thead, tbody and tfoot

The elements thead, tbody and tfoot can be used to semantically enrich your table markup code.

<th>
Used as an alternative to <td> where a cell contains header information. default embolden and centre its content.
<thead>
Groups the table header content (usually containing the column headings).
<tbody>
Contains the main body of the table with all the data rows.
<tfoot>
Less frequently used but typically holds summary information or footnotes

The Correct Use of Tables.

Tables have in the past been used by web designers as a way of laying out content.  However, this technique dates back to the late 1990s when browsers did not have mature CSS support.  CSS is now recognized as the best approach for web page layout.  HTML tables are, however, ideally suited to displaying data.  Tables were made for data. For example:

Styling Tables

Like all HTML elements, tables can be styled with CSS. Common styling to apply are border and padding. The property border-collapse is used to control how table border collapse. It is most commonly set to collapse merging the table borders.

See the Pen Styled HTML table by Martin Cooper (@mustbebuilt) on CodePen.

Tables from the display property

Table like behaviour can be created from non-table elements via the use of the display: table property.

This property can be used to create table-like layouts without using <table> elements.

For example, to create a table-like structure using divs:

With the following CSS:

This CSS creates a table-like layout using div elements, providing more flexibility for styling and responsive design.

See the Pen Table via display by Martin Cooper (@mustbebuilt) on CodePen.

Tip: The display: table technique provides a more flexible, CSS-based approach to creating table-like layouts. It’s ideal when you want the structure of a table but need more control over styling, layout behavior. It also works well with other modern techniques such as flexbox and grid.