HTML Table

What is an HTML Table?

An HTML table is a way to organize data into rows and columns. It’s useful for displaying information like schedules, lists, or comparison charts in a neat, grid-like format.

To create a table in HTML, you use the <table> tag, and inside it, you’ll define rows with the <tr> tag. Each row contains cells, which can either be data cells (<td>) or header cells (<th>).

Basic Structure of an HTML Table

Here’s a simple example of an HTML table:

<table>
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>$1.00</td>
<td>5</td>
</tr>
<tr>
<td>Banana</td>
<td>$0.50</td>
<td>8</td>
</tr>
</tbody>
</table>
  • <table>: Defines the table.
  • <thead>: Contains the header row with column titles.
  • <tbody>: Contains the main data rows.
  • <tr>: Represents a row.
  • <th>: Defines a header cell.
  • <td>: Defines a regular data cell.

Adding More Rows and Columns

You can easily add more rows by copying the <tr> tags, and each row can have as many <td> (data cells) as needed.

Styling the Table

By default, tables don’t look very styled. You can use CSS to add borders, padding, and other styles to make your table more readable.

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

Responsive Tables

For mobile-friendly tables, use CSS to make them adapt to smaller screens:

<style>
@media (max-width: 600px) {
table, th, td {
display: block;
width: 100%;
}
td {
padding-left: 50%;
}
td::before {
content: attr(data-label);
font-weight: bold;
}
}
</style>

Conclusion

HTML tables are a simple and effective way to display structured data. By using the right tags and adding some CSS for styling, you can create clear, organized tables that look good on all devices.