Tables are a fundamental part of web design, used to organize data into rows and columns. In HTML, tables are created using specific tags that define the structure and content of the table. This tutorial will guide you through creating well-structured tables in HTML and how to style them using CSS.
HTML provides several tags to create and structure tables:
<table>: Defines the table.<tr>: Defines a table row.<th>: Defines a header cell within a table row.<td>: Defines a standard data cell within a table row.Additionally, you can use:
<thead>: Groups the header content in a table.<tbody>: Groups the body content in a table.<tfoot>: Groups the footer content in a table.These tags help in organizing and structuring data effectively. Let's dive into some examples to understand how they work.
Here is a simple example of an HTML table:
1<table>2<tr>3<th>Header 1</th>4<th>Header 2</th>5</tr>6<tr>7<td>Data 1</td>8<td>Data 2</td>9</tr>10</table>
<table border="1"> <tr> <th>Header 1</th> <th>Header 2</th> </tr> <tr> <td>Data 1</td> <td>Data 2</td> </tr> </table>
<thead>, <tbody>, and <tfoot>These tags help in organizing the table structure better:
1<table>2<thead>3<tr>4<th>Header 1</th>5<th>Header 2</th>6</tr>7</thead>8<tbody>9<tr>10<td>Data 1</td>11<td>Data 2</td>12</tr>13<tr>14<td>Data 3</td>15<td>Data 4</td>16</tr>17</tbody>18<tfoot>19<tr>20<td>Footer 1</td>21<td>Footer 2</td>22</tr>23</tfoot>24</table>
<table border="1">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
<tr>
<td>Data 3</td>
<td>Data 4</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Footer 1</td>
<td>Footer 2</td>
</tr>
</tfoot>
</table>You can style tables using CSS to make them more visually appealing. Here's an example of how you might style a table:
1<style>2table {3width: 100%;4border-collapse: collapse;5}6th, td {7border: 1px solid #ddd;8padding: 8px;9}10th {11background-color: #f2f2f2;12}13</style>1415<table>16<thead>17<tr>18<th>Header 1</th>19<th>Header 2</th>20</tr>21</thead>22<tbody>23<tr>24<td>Data 1</td>25<td>Data 2</td>26</tr>27<tr>28<td>Data 3</td>29<td>Data 4</td>30</tr>31</tbody>32</table>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
}
th {
background-color: #f2f2f2;
}
</style>
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
<tr>
<td>Data 3</td>
<td>Data 4</td>
</tr>
</tbody>
</table>In the next section, we will explore how to use CSS Media Queries to make your tables responsive and adapt to different screen sizes.
Stay tuned for more advanced topics in HTML and CSS!