Skip to main content

HTML Tables

By SamK
0
0 recommends
Topic(s)

HTML tables provide a row and column structure for web developers to organize and display data, as shown below.

HTML Table Element

HTML Table Components

In HTML, a table consists of various components and tags like <table>, <th>, <tr>, <td>, etc., as shown in the below code.

<table>
  <tr>
    <th>Item</th>
    <th>Qty.</th>
    <th>Price</th>
  </tr>
  <tr>
    <td>Product</td>
    <td>1</td>
    <td>$10</td>
  </tr>
  <tr>
    <td>Product</td>
    <td>2</td>
    <td>$20</td>
  </tr> 
</table> 

The <table> Tag

The main tag for HTML tables is the <table> tag, which encloses all the other tags.

<table>
<tr>
<td></td>
</tr>
</table>

Table Cells

The table cells are defined by the <td> tags. Each cell has an opening <td> tag and a closing </td> tag. The content between <td> and </td> represents the data within the table cell.

<table>
 <tr>
   <td>Product</td>
   <td>1</td>
   <td>$10</td>
 </tr>
</table>

Note: A table cell can contain a variety of HTML elements, such as text, images, lists, links, other tables, and more.

Table Cell Demo

Table Rows

A table row begins with an opening <tr> tag and ends with a closing </tr> tag. The table rows contain the <td> and <th> tags.

<table>
 <tr>
   <th>Item</th>
   <th>Qty.</th>
   <th>Price</th>
 </tr>
 <tr>
   <td>Product</td>
   <td>1</td>
   <td>$10</td>
 </tr>
</table>

You can include as many rows as needed in a table; however, ensure that each row contains the same number of cells.

Table Row Demo

Table Headers

An HTML table may need some header cells in some cases, which can be defined use the <th> tag instead of the <td> tag.

So, the code becomes:

<table>
  <tr>
    <th>Item</th>
    <th>Qty.</th>
    <th>Price</th>
  </tr>
  <tr>
    <td>Product</td>
    <td>1</td>
    <td>$10</td>
  </tr>
  <tr>
    <td>Product</td>
    <td>2</td>
    <td>$20</td>
  </tr>
 <tr>
    <td>Product</td>
    <td>3</td>
    <td>$30</td>
  </tr> 
</table> 

HTML Table Element

By default, text within the <th> tags is bold and centered, but you can modify these styles using CSS. 

For example, in the above preview, we have aligned it to the left of the cell, by using the below CSS.

th {
    text-align: left;
}