HTML Creating Tables
Creating Tables in HTML
HTML tables are used to present data in a structured format. They consist of rows and columns, where each row represents a record and each column represents a field of that record.
Basic Structure of a Table
The basic structure of an HTML table is defined using the following elements:
- <table> - Defines the table.
- <tr> - Defines a table row.
- <th> - Defines a header cell.
- <td> - Defines a standard cell.
Example of a Simple Table
Here’s an example of a simple table:
<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
<tr>
<td>John Doe</td>
<td>30</td>
<td>New York</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>25</td>
<td>Los Angeles</td>
</tr>
</table>
Output of the Simple Table
The above code will render the following table:
| Name | Age | City |
|---|---|---|
| John Doe | 30 | New York |
| Jane Smith | 25 | Los Angeles |
Table Attributes
HTML tables can also have various attributes to control their appearance:
- border - Specifies the width of the border around the table.
- cellpadding - Specifies the space between the cell content and its border.
- cellspacing - Specifies the space between individual table cells.
- width - Sets the width of the table.
Example of Table with Attributes
Here's an example of a table with additional attributes:
<table border="1" cellpadding="10" cellspacing="0" width="50%">
<tr>
<th>Product</th>
<th>Price</th>
</tr>
<tr>
<td>Apple</td>
<td>$1.00</td>
</tr>
<tr>
<td>Banana</td>
<td>$0.50</td>
</tr>
</table>
Output of the Table with Attributes
The above code will render the following table:
| Product | Price |
|---|---|
| Apple | $1.00 |
| Banana | $0.50 |
Table Headers and Footers
HTML also allows the use of <thead>, <tbody>, and <tfoot> elements for grouping table rows:
<table border="1">
<thead>
<tr>
<th>Year</th>
<th>Sales</th>
</tr>
</thead>
<tbody>
<tr>
<td>2021</td>
<td>$1000</td>
</tr>
<tr>
<td>2022</td>
<td>$1500</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total</td>
<td>$2500</td>
</tr>
</tfoot>
</table>
Output of Table with Headers and Footers
The above code will render the following table:
| Year | Sales |
|---|---|
| 2021 | $1000 |
| 2022 | $1500 |
| Total | $2500 |
Nested Tables
You can also create nested tables within a cell of a parent table:
<table border="1">
<tr>
<td>
<table border="1">
<tr>
<td>Nested Cell 1</td>
<td>Nested Cell 2</td>
</tr>
</table>
</td>
</tr>
</table>
Output of Nested Table
The above code will render the following table:
|
Conclusion
HTML tables are a powerful tool for displaying data in a clear and structured way. Understanding how to create and style tables is essential for web development.