HTML Table
HTML tables are used to display data in a tabular format on a webpage. Tables can be used to organize and present a variety of information, such as product lists, pricing tables, schedules, and more.
To create a table in HTML, you use the <table> tag, which creates a container for the table. Within the <table> tag, you can use the following tags to define the structure and content of the table:
- <tr> (table row): Defines a row in the table.
- <th> (table header): Defines a header cell in a row or column. Header cells are typically bold and centered.
- <td> (table data): Defines a data cell in a row or column.
Here's an example of how to create a simple table in HTML:
<html>
<head>
<title>My Table</title>
</head>
<body>
<h1>My Table</h1>
<table>
<tr>
<th>Item</th>
<th>Description</th>
<th>Price</th>
</tr>
<tr>
<td>Widget</td>
<td>A small widget</td>
<td>$10.00</td>
</tr>
<tr>
<td>Gizmo</td>
<td>A large gizmo</td>
<td>$20.00</td>
</tr>
</table>
</body>
</html>
In this example, we have created a table with three columns: Item, Description, and Price. The first row of the table contains the header cells, which are marked with the <th> tag. The remaining rows contain data cells, marked with the <td> tag.
When the webpage is loaded, the table will be displayed with the data in rows and columns, and the header cells will be formatted differently than the data cells to make them stand out. You can use CSS to style the table and change its appearance, such as adding borders, changing colors, and more.
Using colspan
The colspan attribute allows a cell to extend across multiple columns, effectively merging them into one. This can be useful for headers or cells that need to occupy more space than a single column. The value of colspan specifies the number of columns a cell should span.
<table border="1">
<tr>
<th> colspan="2">Merged Header</th>
</tr>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
<tr>
<td> colspan="2">This cell spans across two columns</td>
</tr>
</table>
In this example
- The header row (<tr>) contains a header cell (<th>) with colspan="2", causing it to span across two columns.
- The last row (<tr>) contains a data cell (<td>) with colspan="2", allowing it to occupy both columns in that row.