HTML Tables

Tables are used in HTML to display data in a tabular (row and column) format. HTML provides specific tags to define the structure and content of tables.


Creating a Table in HTML

To create a basic table, you use the <table> tag along with <tr> (table row), <th> (table header), and <td> (table data) elements.

<table>
  <tr>
    <th>Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Alice</td>
    <td>24</td>
  </tr>
  <tr>
    <td>Bob</td>
    <td>30</td>
  </tr>
</table>

Table Rows and Cells

- <tr> defines a row.
- <td> defines a data cell.
- <th> defines a header cell (bold and centered by default).


Table Headers, Captions, and Footers

You can enhance table semantics using headers, captions, and footers.

<table>
  <caption>Student Scores</caption>
  <thead>
    <tr>
      <th>Name</th>
      <th>Score</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Ravi</td>
      <td>85</td>
    </tr>
    <tr>
      <td>Meena</td>
      <td>90</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Total Students</td>
      <td>2</td>
    </tr>
  </tfoot>
</table>
  • <caption>: Describes the table.
  • <thead>: Contains header rows.
  • <tbody>: Main data of the table.
  • <tfoot>: Footer row (often used for summaries).

Merging Cells (colspan, rowspan)

You can merge cells horizontally using colspan and vertically using rowspan.

<table border="1">
  <tr>
    <th colspan="2">Employee Details</th>
  </tr>
  <tr>
    <td>Name</td>
    <td>John</td>
  </tr>
  <tr>
    <td rowspan="2">Contact</td>
    <td>Email: john@example.com</td>
  </tr>
  <tr>
    <td>Phone: 123-456-7890</td>
  </tr>
</table>
  • colspan="2": Merges two columns into one.
  • rowspan="2": Merges two rows into one.

Styling HTML Tables with CSS

You can style tables using CSS to improve appearance and readability.

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

<table>
  <tr>
    <th>Country</th>
    <th>Capital</th>
  </tr>
  <tr>
    <td>India</td>
    <td>New Delhi</td>
  </tr>
</table>

Styling helps make tables more readable and visually appealing.


Conclusion

Tables are ideal for displaying structured data. With support for headers, footers, cell merging, and CSS styling, you can create rich and informative data layouts on your webpage.

Up next, we will explore HTML Forms to learn how to collect user input through text fields, checkboxes, radio buttons, and more.

If you have any questions, feel free to ask. Thank you for reading!

Thankyou!