In HTML, tables are created using the <table> tag, and the structure of a table includes several key elements: table rows (<tr>), table headers (<th>), and table data (<td>). Below is the basic structure of a table:
<table> <tr> <th>Header 1</th> <th>Header 2</th> <th>Header 3</th> </tr> <tr> <td>Data 1</td> <td>Data 2</td> <td>Data 3</td> </tr> <tr> <td>Data 4</td> <td>Data 5</td> <td>Data 6</td> </tr> </table>
| Header 1 | Header 2 | Header 3 |
|---|---|---|
| Data 1 | Data 2 | Data 3 |
| Data 4 | Data 5 | Data 6 |
This simple table consists of three columns, each with a header row (<th>) followed by two rows of data (<td>).
Tables can be styled with CSS to change their appearance, including borders, spacing, and alignment.
Example of adding a border to a table:
table, th, td { border: 1px solid black; }
This will add a black border around the entire table, as well as each header and data cell.
Example of adjusting padding and text alignment:
table { width: 100%; } th, td { padding: 8px; text-align: left; }
This will add padding inside each table cell and align the text to the left.
You can merge cells in a table by using the `rowspan` and `colspan` attributes. These allow one cell to span multiple rows or columns.
<table> <tr> <th>Header 1</th> <th colspan="2">Header 2 & 3</th> </tr> <tr> <td rowspan="2">Row 1-2</td> <td>Data 1</td> <td>Data 2</td> </tr> <tr> <td>Data 3</td> <td>Data 4</td> </tr> </table>
| Header 1 | Header 2 & 3 | |
|---|---|---|
| Row 1-2 | Data 1 | Data 2 |
| Data 3 | Data 4 | |
This table has a header row where the second and third columns are merged with colspan=”2″, and the first cell in the second row spans two rows using rowspan=”2″.
You can also nest tables inside other tables. This is useful for more complex layouts, such as when you want to add a table inside a table cell.
<table>
<tr>
<th>Main Head 1</th>
<th>Main Head 2</th>
</tr>
<tr>
<td>
<table>
<tr>
<th>Sub Head 1</th>
<th>Sub Head 2</th>
</tr>
<tr>
<td>Sub Data 1</td>
<td>Sub Data 2</td>
</tr>
</table>
</td>
<td>Main Data 2</td>
</tr>
</table>
| Main Head 1 | Main Head 2 | ||||
|---|---|---|---|---|---|
|
Main Data 2 |
In this example, the first column contains a nested table with its own rows and columns.
When designing tables for smaller screens, it’s important to ensure that the table content adjusts properly. You can make tables responsive using CSS.
Example of making a table responsive:
table { width: 100%; table-layout: auto; overflow-x: auto; display: block; }
This will make the table scrollable horizontally on small screens, ensuring that it remains readable.