Premium HTML Course

6. HTML Tables

HTML tables allow you to organize and display data in a grid format, making it easier to read and understand structured data. Tables are created using the <table> element, and they consist of rows, columns, and cells.

Basic Table Syntax

A simple HTML table is structured with the following elements:


<table>
  <tr>
    <th>Header 1</th>
    <th>Header 2</th>
  </tr>
  <tr>
    <td>Data 1</td>
    <td>Data 2</td>
  </tr>
</table>
        

In this example, the <table> element defines the table, the <tr> defines each table row, the <th> defines the table headers, and the <td> defines the table data cells.

Table Structure

A table generally consists of the following elements:

Example: Basic Table

This is an example of a basic table with two rows and two columns:


<table>
  <tr>
    <th>Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>John Doe</td>
    <td>25</td>
  </tr>
  <tr>
    <td>Jane Smith</td>
    <td>30</td>
  </tr>
</table>
        

This simple table displays a list of names and ages, with headers for each column.

Styling Tables

You can style tables using CSS to make them more visually appealing. Here is an example of how to add borders, spacing, and text alignment:


table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

th {
  background-color: #f2f2f2;
}
        

This CSS rule applies to the entire table, making the header cells have a different background color and adding borders to both the headers and data cells.

Example: Styled Table

Here's an example of a table with styling:


<table>
  <tr>
    <th>Product</th>
    <th>Price</th>
  </tr>
  <tr>
    <td>Laptop</td>
    <td>$799</td>
  </tr>
  <tr>
    <td>Smartphone</td>
    <td>$499</td>
  </tr>
</table>
        

This table shows product names and their corresponding prices. It has the same styles applied as the previous CSS example.

Advanced Table Features

HTML tables offer several advanced features, including:

Example: Table with Caption and Spanning Cells


<table>
  <caption>Product List</caption>
  <tr>
    <th>Product</th>
    <th>Price</th>
    <th>Category</th>
  </tr>
  <tr>
    <td colspan="2">Laptop</td>
    <td>$799</td>
  </tr>
</table>
        

This table includes a caption and uses colspan to span two columns for the product name.

Conclusion

HTML tables are a powerful tool for organizing and displaying data in a structured way. By using different table elements, you can create complex data layouts. In the next lesson, we will explore HTML multimedia elements, such as images, videos, and audio.