Tables in HTML

Definition

HTML tables are used to display data in a structured format using rows and columns.
They are commonly used for reports, records, schedules, and comparison data.

1. Table Structure

An HTML table is made up of rows, and each row contains cells.

Basic Structure

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

2. Table Tags Explained

2.1 <table> Tag

  • Defines the table
  • Acts as a container for all table elements

<table>...</table>

2.2 <tr> (Table Row)

  • Defines a row inside the table
  • Each row can contain headers or data

<tr>...</tr>

2.3 <th> (Table Header)

  • Defines header cells
  • Text is bold and centered by default
  • Used for headings

<th>Name</th>

2.4 <td> (Table Data)

  • Defines data cells
  • Normal text, left-aligned by default

<td>Table  data</td>

3. Complete Table Example

<table border="1">
   <tr>
       <th>Name</th>
       <th>Age</th>
       <th>Course</th>
   </tr>
   <tr>
       <td>Ashutosh</td>
       <td>22</td>
       <td>CSE</td>
   </tr>
   <tr>
       <td>Rahul</td>
       <td>21</td>
       <td>IT</td>
   </tr>
</table>

Output

A table with 3 columns and 3 rows, clearly showing student data.

4. Rowspan

Definition

rowspan is used to merge two or more rows into one cell.

Syntax

<td rowspan="2">Value</td>

Example

<table border="1">
   <tr>
       <th>Name</th>
       <th>Subject</th>
   </tr>
   <tr>
       <td rowspan="2">Ashu</td>
       <td>Math</td>
   </tr>
   <tr>
       <td>Science</td>
   </tr>
</table>

output

Explanation

  • The name Ashu spans two rows
  • One cell covers multiple rows

5. Colspan

Definition

colspan is used to merge two or more columns into one cell.

Syntax

<td colspan="2">Value</td>

Example

<table border="1">
   <tr>
       <th>Name</th>
       <th colspan="2">Marks</th>
   </tr>
   <tr>
       <td>Ashu</td>
       <td>45</td>
       <td>48</td>
   </tr>
</table>

output

Explanation

  • The Marks header spans two columns
  • Columns are merged horizontally

6. Difference Between Rowspan and Colspan

RowspanColspan
Merges rowsMerges columns
Vertical mergeHorizontal merge
Uses rowspanUses colspan

7. Important Points

  • Tables are row-based
  • <th> is for headings
  • <td> is for data
  • rowspan and colspan reduce cell count
  • Use tables only for data, not layout