HTML Tables:
HTML tables are used to organize and present data in a structured format on a web page. Tables consist of rows and columns, and they are an essential part of web development for displaying various types of information.
Here's a detailed guide on using HTML tables:- Basic Structure:
- The basic structure of an HTML table involves the use of three main elements: <table>, <tr>, and <td>.
- Table Elements:
- <table>: The container element for the entire table.
- <tr>: Represents a table row. It contains one or more <td> or <th> elements.
- <td>: Stands for table data and represents a standard cell within a table.
- <th>: Stands for table header and represents a header cell, typically used for column or row headings.
- Table Headers:
- The <th> element is used to define header cells in a table. Header cells are usually bold and centered.
- Table Captions:
- The <caption> element is used to add a caption or title to the table.
- Table Borders and Styles:
- CSS can be used to add borders, colors, and styles to the table for better presentation.
<table>
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>
Output:-
| Row 1, Column 1 | Row 1, Column 2 |
| Row 2, Column 1 | Row 2, Column 2 |
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>
Output:-
| Heading 1 | Heading 2 |
| Data 1 | Data 2 |
<table>
<caption>My Table</caption>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>
Output:-
| Header 1 | Header 2 |
|---|---|
| Data 1 | Data 2 |
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
Example:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML Table Example</title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}</style>
</head>
<body>
<h1>Sample Table</h1>
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
<tr>
<td>John Doe</td>
<td>25</td>
<td>New York</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>30</td>
<td>San Francisco</td>
</tr>
</table>
</body>
</html>
Example:-
Sample Table
| Name | Age | City |
|---|---|---|
| John Doe | 25 | New York |
| Jane Smith | 30 | San Francisco |