What are HTML Tables?
HTML tables are used to display data in a structured format, organized in rows and columns. They are useful for presenting tabular data such as schedules, financial data, and more.
Table Syntax
The basic syntax for creating a table in HTML is as follows:
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>
Example:
<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Alice</td>
<td>30</td>
</tr>
<tr>
<td>Bob</td>
<td>25</td>
</tr>
</table>
Common Table Attributes
Tables can have several attributes to control their appearance:
- border: Specifies the border width of the table.
- cellpadding: Specifies the space between the cell border and its content.
- cellspacing: Specifies the space between individual cells.
- width: Specifies the width of the table (e.g., in pixels or percentage).
Example of a table with attributes:
<table border="1" cellpadding="5">
Example of a Table
Name | Age | City |
---|---|---|
Alice | 30 | New York |
Bob | 25 | Los Angeles |
Charlie | 35 | Chicago |
Best Practices for Using HTML Tables
- Use tables for tabular data only, not for layout purposes.
- Include header rows using
<th>
for better accessibility. - Keep tables simple and avoid unnecessary complexity.
- Consider responsive design for tables on smaller screens.