Table headers help organize data by labeling columns or rows. They make tables easier to understand and navigate.
0
0
Table headers in HTML
Introduction
When you want to label columns in a data table, like names or dates.
When you need to describe rows for better clarity, such as categories or items.
When making tables accessible for screen readers to understand the structure.
When you want to style headers differently to highlight them visually.
When creating reports or schedules that need clear headings.
Syntax
HTML
<thead> <tr> <th>Header 1</th> <th>Header 2</th> </tr> </thead>
The <th> tag defines a table header cell.
Headers are usually inside a <thead> section but can also appear in <tbody> or <tfoot>.
Examples
Simple table with column headers for Name, Age, and City.
HTML
<table> <thead> <tr> <th>Name</th> <th>Age</th> <th>City</th> </tr> </thead> </table>
Headers used directly inside the table without
<thead>.HTML
<table> <tr> <th>Product</th> <th>Price</th> </tr> <tr> <td>Apple</td> <td>$1</td> </tr> </table>
Using
scope attribute to specify if header is for a column or row, improving accessibility.HTML
<table> <thead> <tr> <th scope="col">Date</th> <th scope="col">Event</th> </tr> </thead> <tbody> <tr> <th scope="row">2024-06-01</th> <td>Meeting</td> </tr> </tbody> </table>
Sample Program
This example shows a simple table with headers for Name, Role, and Location. The headers have a green background and white text to stand out. The table is centered and easy to read.
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Table Headers Example</title> <style> table { border-collapse: collapse; width: 100%; max-width: 400px; margin: 1rem auto; font-family: Arial, sans-serif; } th, td { border: 1px solid #333; padding: 0.5rem 1rem; text-align: left; } th { background-color: #4CAF50; color: white; } </style> </head> <body> <main> <h1>Team Members</h1> <table> <thead> <tr> <th>Name</th> <th>Role</th> <th>Location</th> </tr> </thead> <tbody> <tr> <td>Alice</td> <td>Developer</td> <td>New York</td> </tr> <tr> <td>Bob</td> <td>Designer</td> <td>London</td> </tr> <tr> <td>Charlie</td> <td>Manager</td> <td>Tokyo</td> </tr> </tbody> </table> </main> </body> </html>
OutputSuccess
Important Notes
Always use <th> for headers, not <td>, to help screen readers.
The scope attribute on <th> improves accessibility by clarifying if the header is for a row or column.
Use CSS to style headers differently so users can easily spot them.
Summary
Table headers label columns or rows to organize data clearly.
Use <th> tags inside <thead> or directly in rows.
Headers improve readability and accessibility for all users.