HTML Tables

ADVERTISEMENT

Tables in HTML are super useful when you need to organize information in rows and columns, like pricing charts, schedules, or comparisons.

Let’s break it down step-by-step with practical examples.

📐 Basic Table Structure

HTML tables are made up of:

  • <table> – wraps the entire table
  • <tr> – table row
  • <th> – table header (bold + centered by default)
  • <td> – table data (regular cell)

✅ Example:

<table>
  <tr>
    <th>Course</th>
    <th>Duration</th>
  </tr>
  <tr>
    <td>HTML</td>
    <td>2 Weeks</td>
  </tr>
  <tr>
    <td>CSS</td>
    <td>3 Weeks</td>
  </tr>
</table>

🧠 Table headers automatically make the content bold and centered.

🔗 rowspan & colspan – Merging Cells

🔼 rowspan – Merge rows vertically

<td rowspan="2">Frontend</td>

🔽 colspan – Merge columns horizontally

<th colspan="2">Course Details</th>

🧪 Example with Both:

<table border="1">
  <tr>
    <th rowspan="2">Course</th>
    <th colspan="2">Duration</th>
  </tr>
  <tr>
    <td>Weeks</td>
    <td>Hours</td>
  </tr>
  <tr>
    <td>HTML</td>
    <td>2</td>
    <td>20</td>
  </tr>
</table>

🧭 Table Head, Body, and Foot

HTML5 supports semantic grouping:

  • <thead>: table header rows
  • <tbody>: main content rows
  • <tfoot>: footer row(s)

✅ Example:

<table border="1">
  <thead>
    <tr>
      <th>Item</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Pen</td>
      <td>$1</td>
    </tr>
    <tr>
      <td>Notebook</td>
      <td>$2</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Total</td>
      <td>$3</td>
    </tr>
  </tfoot>
</table>

🧠 Bonus: <thead>, <tbody>, and <tfoot> are useful for screen readers and JavaScript sorting plugins.

🎨 Basic Table Styling (Inline or CSS)

You can style tables inline or via CSS.

Inline example:

<table border="1" style="border-collapse: collapse; width: 100%;">
  <tr style="background-color: #f0f0f0;">
    <th>Name</th>
    <th>Email</th>
  </tr>
  <tr>
    <td>John</td>
    <td>john@example.com</td>
  </tr>
</table>

CSS version:

table {
  border-collapse: collapse;
  width: 100%;
}
th, td {
  border: 1px solid #ccc;
  padding: 8px;
}
th {
  background-color: #f9f9f9;
  text-align: left;
}

✅ Summary Table

TagPurpose
<table>Main table wrapper
<tr>Table row
<th>Header cell
<td>Data cell
rowspanMerge cells vertically
colspanMerge cells horizontally
<thead> / <tbody> / <tfoot>Grouping sections for structure and accessibility

🧪 Practice It Yourself

<table border="1">
  <thead>
    <tr>
      <th>Subject</th>
      <th>Marks</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Math</td>
      <td>95</td>
    </tr>
    <tr>
      <td>Science</td>
      <td>90</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Total</td>
      <td>185</td>
    </tr>
  </tfoot>
</table>

🎓 Coming Up Next:

Let’s learn how to collect user data with HTML Forms.

📚 Next: HTML Forms

ADVERTISEMENT