Tables in HTML are used to display data in a structured format. They are useful for presenting information like schedules, reports, and pricing tables. The main HTML elements for tables are:
<table>
: Defines the table.<tr>
: Defines a row.<td>
: Defines a cell.<th>
: Defines a header cell.
Basic Table Structure
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>
Explanation
- The
<th>
tag makes header cells bold. - The
border
attribute adds a border (use CSS for better styling).
Adding More Rows and Columns
<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
<tr>
<td>John</td>
<td>25</td>
<td>New York</td>
</tr>
<tr>
<td>Jane</td>
<td>30</td>
<td>London</td>
</tr>
</table>
Run Code on FunProgramming
Merging Cells: colspan
and rowspan
Use colspan
to merge columns and rowspan
to merge rows.
<table border="1">
<tr>
<th colspan="2">Merged Header</th>
</tr>
<tr>
<td rowspan="2">Merged Row</td>
<td>Row 1</td>
</tr>
<tr>
<td>Row 2</td>
</tr>
</table>
Run Code on FunProgramming
Styling Tables with CSS
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 10px;
text-align: left;
}
th {
background-color: lightgray;
}
</style>
Run Code on FunProgramming
Fun Facts About Tables
- Tables were once used for entire webpage layouts before CSS became popular!
- Using too many tables can make your page slow.
<th>
improves accessibility as screen readers recognize it as a header.
Conclusion
HTML tables are powerful for structuring data. Use them wisely, style them with CSS, and avoid excessive use for layout design!
0 Comments