HTML Tables

HTML tables are defined with the <table> tag. A table is divided into rows using the <tr> tag (tr= table row). A row is divided into data cells using the <td> tag (td= table data). A row can also be divided into headings using the <th> tag (th= table heading).

The <td> elements can contain all sorts of HTML elements like text, images, lists, other tables, etc. You can specify the width of a table using some CSS.

<table style=“width:300px”>
<tr>
   <td>Joey</td>
   <td>Alabbassi</td>
   <td>2014</td>
</tr>
<tr>
   <td>Yusif</td>
   <td>Alabbassi</td>
   <td>2015</td>
</tr>
</table>

 

HTML Table with a Border

Unless you specify a table to have border, it will be displayed without any borders. You can add a border to your table using the border attribute. 

<table border=“1” style=“width:300px”>
<tr>
   <td>Joey</td>
   <td>Alabbassi</td>
   <td>2014</td>
</tr>
<tr>
   <td>Yusif</td>
   <td>Alabbassi</td>
   <td>2015</td>
</tr>
</table>

NOTE: The border attribute is on its way out of the HTML standard, so it’s better to use CSS.

<style>
table,th,td
{
border:1px solid black;
}
</style>

 

Collapsed Borders

If you want your border to collapse into one border, add border-collapse to your CSS.

<style>
table,th,td
{
border:1px solid black;
border-collapse:collapse
}
</style>

 

Cell Padding

Cell padding specifies the space between the content in the cell and its border. Without specifying a padding, the table cells will be displayed without any padding. Use the CSS padding property to set the padding:

th,td
{
padding:5px;
}

 

Cell Spacing

To specify the space between the cells, use the CSS border-spacing property:

table
{
border-spacing:5px;
}

 

HTML Table Headings

Table headings are defined using the <th> tag (th= table heading). All major browsers will by default display table headings as bold and centered: 

<table style=“width:300px”>
<tr>
   <th>First Name</th>
   <th>Last Name</th>
   <th>Year</th>
</tr>
<tr>
   <td>Joey</td>
   <td>Alabbassi</td>
   <td>2014</td>
</tr>
</table>

 

To left-align the headings, use the CSS text-align property:

th
{
text-align:left;
}
 

First Name Last Name Year
Joey Alabbassi 2014
John Doe 2015
Jane Smith 2016
Lucas Skywalker 2020