HTML Tables - Detailed Overview

Introduction to HTML Tables

HTML tables allow you to organize data into rows and columns. They are commonly used to display tabular data on webpages. This guide covers the basic structure of HTML tables and how to style them effectively.

Basic Table Structure

An HTML table is defined with the <table> tag. Inside the table, you can use the <tr> tag for table rows, <th> for table headers, and <td> for table data cells. Here’s an example:

<table>
    <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Country</th>
    </tr>
    <tr>
        <td>John</td>
        <td>30</td>
        <td>USA</td>
    </tr>
    <tr>
        <td>Anna</td>
        <td>25</td>
        <td>UK</td>
    </tr>
</table>

The above code will create the following table:

Name Age Country
John 30 USA
Anna 25 UK

Table Borders and Styling

You can add borders to your table and style it using CSS. For example, you can add padding to cells, set border colors, and apply background colors to the header row:

table {
    width: 100%;
    border-collapse: collapse;
}
th, td {
    border: 1px solid #ddd;
    padding: 8px;
}
th {
    background-color: #f4f4f4;
}

The above CSS will style the table like this:

Name Age Country
John 30 USA
Anna 25 UK

Advanced Table Features

HTML tables also support more advanced features such as row and column spans. These allow cells to span across multiple rows or columns:

<table>
    <tr>
        <th rowspan="2">Name</th>
        <th colspan="2">Details</th>
    </tr>
    <tr>
        <th>Age</th>
        <th>Country</th>
    </tr>
    <tr>
        <td>John</td>
        <td>30</td>
        <td>USA</td>
    </tr>
</table>

This code creates a table with merged cells like this:

Name Details
Age Country
John 30 USA