Web Development - HTML Tables
HTML Tables
Tables are used to organize data into rows and columns.
In HTML, a table is created with the <table> element.
Basic Table
A simple table is built using table rows (<tr>) and table data cells (<td>).
Example
Simple HTML table:
<table>
<tr>
<td>HTML</td>
<td>CSS</td>
<td>JavaScript</td>
</tr>
</table>
Try it Yourself »
Each table row (<tr>) defines a horizontal line of cells, and each cell (<td>) holds data.
Adding Borders
By default, tables have no borders.
You can add borders with the border attribute,
or better yet, use CSS:
Example
Adding borders with CSS:
<table style="border:1px solid black;">
<tr>
<td>Apple</td>
<td>Banana</td>
</tr>
<tr>
<td>Cherry</td>
<td>Mango</td>
</tr>
</table>
Try it Yourself »
Table Headers
Use the <th> element for table headers.
Header cells are bold and centered by default.
Example
Table with headers:
<table style="border:1px solid black;">
<tr>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
<tr>
<td>Anna</td>
<td>24</td>
<td>Norway</td>
</tr>
<tr>
<td>John</td>
<td>30</td>
<td>USA</td>
</tr>
</table>
Try it Yourself »
Table Borders and Cell Spacing
To make borders look cleaner, you can collapse them with border-collapse: collapse;.
You can also add padding to make cells easier to read.
Example
Styled table:
<table style="border-collapse: collapse; width: 100%;">
<tr>
<th style="border:1px solid #000; padding:8px;">Name</th>
<th style="border:1px solid #000; padding:8px;">Age</th>
<th style="border:1px solid #000; padding:8px;">Country</th>
</tr>
<tr>
<td style="border:1px solid #000; padding:8px;">Lisa</td>
<td style="border:1px solid #000; padding:8px;">22</td>
<td style="border:1px solid #000; padding:8px;">Sweden</td>
</tr>
</table>
Try it Yourself »
Table Caption
The <caption> tag adds a title to your table.
Example
Table with caption:
<table style="border:1px solid black;">
<caption>Student Grades</caption>
<tr>
<th>Name</th>
<th>Grade</th>
</tr>
<tr>
<td>Tom</td>
<td>A</td>
</tr>
</table>
Try it Yourself »
Spanning Columns and Rows
You can merge cells using the colspan and rowspan attributes.
Example
Merging cells:
<table style="border:1px solid black;">
<tr>
<th colspan="2">Name</th>
</tr>
<tr>
<td>First</td>
<td>Last</td>
</tr>
<tr>
<td rowspan="2">Age</td>
<td>25</td>
</tr>
<tr>
<td>30</td>
</tr>
</table>
Try it Yourself »
Best Practices
- Always include a table header row to describe the data.
- Use CSS for borders and styling instead of the
borderattribute. - Keep tables simple for accessibility and readability.
Tip: Use tables only for data, not for page layout. Layout is done with CSS.
Summary
<table>- creates a table<tr>- defines a table row<th>- defines a table header<td>- defines a data cellcolspanandrowspan- merge cells
Next, you will learn about HTML Blocks and Inline Elements - understanding how elements behave on a web page.
Next » HTML Blocks and Inline Elements