Skip to content
Azril Hakim
LinkedInGitHub

Tables

HTML tables are a useful way to organize and display tabular data on a web page. In this section, we will cover the basics of creating and formatting tables in HTML.

Creating Tables

To create a table in HTML, you use the <table> element. A table consists of rows and columns. Each row is defined using the <tr> (table row) element, and within each row, you can have table data cells defined using the <td> (table data) element. Here’s a simple example:

<table>
  <tr>
    <td>Row 1, Column 1</td>
    <td>Row 1, Column 2</td>
  </tr>
  <tr>
    <td>Row 2, Column 1</td>
    <td>Row 2, Column 2</td>
  </tr>
</table>

This code creates a basic table with two rows and two columns.

Table Headers (<th>)

In addition to regular table data cells (<td>), you can use table header cells (<th>) to define headers for rows or columns. Header cells are typically bold and centered by default, making it easy to distinguish them from regular data cells. Here’s an example:

<table>
  <tr>
    <th>Name</th>
    <th>Age</th>
    <th>City</th>
  </tr>
  <tr>
    <td>John</td>
    <td>25</td>
    <td>New York</td>
  </tr>
  <tr>
    <td>Alice</td>
    <td>30</td>
    <td>Los Angeles</td>
  </tr>
</table>

In this example, the first row contains table header cells.

Merging Cells (colspan and rowspan)

HTML allows you to merge cells both horizontally and vertically to create complex table structures. You can use the colspan attribute to merge cells horizontally and the rowspan attribute to merge cells vertically.

Horizontal Cell Merging (colspan)

Suppose you want to create a table cell that spans two columns. You can use the colspan attribute to achieve this:

<table>
  <tr>
    <th>Name</th>
    <th colspan="2">Contact Information</th>
  </tr>
  <tr>
    <td>John</td>
    <td>Email: john@example.com</td>
    <td>Phone: 555-1234</td>
  </tr>
</table>

In this example, the “Contact Information” header cell spans two columns.

Vertical Cell Merging (rowspan)

To merge cells vertically, you can use the rowspan attribute:

<table>
  <tr>
    <th>Name</th>
    <th>Contact Information</th>
  </tr>
  <tr>
    <td rowspan="2">John</td>
    <td>Email: john@example.com</td>
  </tr>
  <tr>
    <td>Phone: 555-1234</td>
  </tr>
</table>

In this example, the “Name” cell spans two rows.

HTML tables are a versatile tool for presenting structured data on your web pages. By understanding how to create tables, use header cells, and merge cells, you can create organized and visually appealing tables for your web content.