HTML Tables: Table, TR, TD, TH, Caption, Colspan, Rowspan & Styling Guide

1. What is the purpose of the <table> element in HTML?

Q: What is the purpose of the table element in HTML?

The <table> element is used to display tabular data in rows and columns, ideal for presenting structured information like schedules or data sets.

2. How do you create a basic table in HTML? Provide an example.

Q: How do you create a basic table in HTML?

A basic table is created using the <table> tag, with <tr> for rows, <th> for headers, and <td> for data cells.

<table>
  <tr>
    <th>Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>John</td>
    <td>25</td>
  </tr>
  <tr>
    <td>Jane</td>
    <td>30</td>
  </tr>
</table>
      

3. How do you add a caption to a table in HTML?

Q: How do you add a caption to a table in HTML?

Use the <caption> tag immediately after the <table> tag to provide a title or description for the table.

<table>
  <caption>Employee Data</caption>
  <tr>
    <th>ID</th>
    <th>Name</th>
  </tr>
  <tr>
    <td>001</td>
    <td>Alice</td>
  </tr>
</table>
      

4. How can you merge cells in a table?

Q: How can you merge cells in a table?

Use the rowspan attribute to merge cells vertically or colspan to merge cells horizontally on <td> or <th> elements.

<table>
  <tr>
    <th colspan="2">Merged Header</th>
  </tr>
  <tr>
    <td>Cell 1</td>
    <td rowspan="2">Vertical Merge</td>
  </tr>
  <tr>
    <td>Cell 2</td>
  </tr>
</table>
      

5. How do you style a table with borders using CSS?

Q: How do you style a table with borders using CSS?

Apply the CSS border property to the <table>, <th>, and <td> elements, often with border-collapse for cleaner borders.

<style>
table, th, td {
  border: 1px solid #000;
  border-collapse: collapse;
}
th, td {
  padding: 8px;
}
</style>
      

6. What is the role of the <thead>, <tbody>, and <tfoot> tags?

Q: What is the role of thead, tbody, and tfoot tags?

These tags organize table content:

7. Write the HTML code for a table with a header and two rows of data.

Q: Write the HTML code for a table with a header and two rows of data.

<table>
  <thead>
    <tr>
      <th>Product</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Laptop</td>
      <td>$999</td>
    </tr>
    <tr>
      <td>Phone</td>
      <td>$499</td>
    </tr>
  </tbody>
</table>