HTML Tables

An HTML table shows data in rows and columns. Tables are for data, like a price list or a timetable. Do not use tables to design the layout of a page; use CSS for that.


Basic table

<table>
  <tr>
    <th>Name</th>
    <th>Marks</th>
  </tr>
  <tr>
    <td>Robin</td>
    <td>85</td>
  </tr>
  <tr>
    <td>Maria</td>
    <td>92</td>
  </tr>
</table>
Output in the browser
Name Marks
Robin 85
Maria 92

TagMeaning
<table>The whole table
<tr>Table row
<th>Header cell. Bold and centered by default
<td>Data cell

Borders and spacing with CSS

A table has no border by default. Add borders with CSS. border-collapse: collapse joins the double borders into one.

<style>
  table { border-collapse: collapse; width: 100%; }
  th, td { border: 1px solid #999; padding: 8px; text-align: left; }
  th { background: #eee; }
</style>

Caption, head, body and foot

For bigger tables, group the rows. This helps with styling and accessibility.

<table>
  <caption>Monthly sales</caption>
  <thead>
    <tr><th>Month</th><th>Sales</th></tr>
  </thead>
  <tbody>
    <tr><td>January</td><td>500</td></tr>
    <tr><td>February</td><td>700</td></tr>
  </tbody>
  <tfoot>
    <tr><td>Total</td><td>1200</td></tr>
  </tfoot>
</table>
Output in the browser
Monthly sales
Month Sales
January 500
February 700
Total 1200

Note: Old attributes like border, cellpadding, cellspacing and bgcolor on the table tag are not used in HTML5. Use CSS.

To join cells, read Rowspan and Colspan.


Summary

  • Use table, tr, th and td to make a table.
  • Use thead, tbody, tfoot and caption for structure.
  • Style tables with CSS and do not use them for page layout.
  • Next: Rowspan and Colspan.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.