HTML

Introduction to Web and HTML

How the Web Works What is HTML Why Learn HTML

Table Structure

Table Structure

HTML tables are used to display data in a structured, organized format. Tables are composed of rows and columns, with each cell containing data or other HTML elements. In this section, we'll explore how to create and structure tables in HTML.

Creating a Basic Table

To create a basic HTML table, you need the following elements:

  • <table>: This element defines the entire table.
  • <tr>: This element represents a table row.
  • <th>: Use this element for table headers (optional).
  • <td>: Use this element for table data cells.

Here's an example of a simple table:

<table>
  <tr>
    <th>Header 1</th>
    <th>Header 2</th>
  </tr>
  <tr>
    <td>Data 1</td>
    <td>Data 2</td>
  </tr>
  <tr>
    <td>Data 3</td>
    <td>Data 4</td>
  </tr>
</table>

Table Headers

Headers in a table are typically defined using the <th> element. They provide context and describe the content of the data cells in that column. Browsers often render table headers in bold or with additional styling.

Table Captions

You can also add a caption to describe the table's content. To do this, use the <caption> element, which should be placed within the <table> element, but before any rows.

<table>
  <caption>Monthly Expenses</caption>
  <tr>
    <th>Category</th>
    <th>Amount</th>
  </tr>
  <!-- Data rows -->
</table>

Spanning Rows and Columns

You can use the rowspan and colspan attributes to make a cell span multiple rows or columns, which is useful for creating merged cells.

<table>
  <tr>
    <th rowspan="2">Header 1</th>
    <th>Header 2</th>
  </tr>
  <tr>
    <td>Data 1</td>
    <td>Data 2</td>
  </tr>
</table>

Styling Tables

You can apply CSS styles to tables and their elements to control the layout, borders, and overall appearance of the table.

Here's an example of CSS for styling tables:

table {
  border-collapse: collapse;
  width: 100%;
  border: 1px solid #ccc;
}

th, td {
  border: 1px solid #ccc;
  padding: 8px;
  text-align: left;
}

th {
  background-color: #f2f2f2;
  font-weight: bold;
}

Accessibility

When creating tables, consider accessibility. Use proper table headers and captions, and ensure that data is organized in a meaningful way for screen readers.

In summary, HTML tables are an effective way to present structured data on a web page. You can use elements like <table>, <tr>, <th>, and <td> to create tables and enhance their appearance with CSS. Always aim for an accessible and well-structured design when using tables on your website.