HTML TABLE


For better presentation of data sometimes we need to create tables.

For that we need to arrange our data values in form of row and column.In HTML we can do this using the <table> tag followed by other tags like: <tr> tag, <th> tag and <td> tag.

Lets see an example:

Example:

Name Age Hobby
Jack 21 Learning
Jenny 25 Exploration
John 20 Entertainment
Jerry 5 Playing

<table style="width:100%" border="1">
<tr>
  <th>Name</th>
  <th>Age</th>
  <th>Hobby</th>
</tr>
<tr>
  <td>John (Author)</td>
  <td>21</td>
  <td>Learning</td>
</tr>
<tr>
  <td>Jeany</td>
  <td>25</td>
  <td>Exploring</td>
</tr>
<tr>
  <td>jerry</td>
  <td>5</td>
  <td>Playing</td>
</tr>
</table>
Try It

Explanation:

Note: Inside <tr> tag we can insert any HTML element including data,text,list,image,other table etc.


HTML Table - Border

For creating borders around the table's row and column either we need to use the border attribute in <table> tag(as we did in above example) or we can create border using CSS.

Here is an example of creating border using:

table, td, th {
border: 1px solid black ;
}
Try It

HTML Table - Border collapse

As we can see in above both examples borders are not collapsed.To create a collapsed border table we need to use CSS property border-collapse:collapse.

table, td, th {
border: 1px solid black ;
border-collapse: collapse ;
}
Try It

HTML Table - cell spanning multiple rows or column

Generally cells of a table span only one row and one column but we can increase their spanning to multiple rows or columns.

For spanning multiple rows or columns we can use the attribute rowspan for multiple row span and colspan for multiple column span.

As we can see in the example below:

<table style="width:100%" border="1">
<tr>
  <th>Name</th>
  <th colspan="2">Books</th>
</tr>
<tr>
  <th rowspan="2">Shakespeare</th>
  <td>King Lear</td>
  <td>Romeo and juliet</td>
</tr>
<tr>
  <th>Chetan Bhagat</th>
  <td>3 mistakes of my life</td>
  <td>Half Girlfriend</td>
</tr>
</table>
Try It

HTML Table - Caption

We can add caption to any table.Caption provides basic information about the table.

For creating a caption to the table <caption> tag is used.This tag must be immediately used after the table tag.

<table style="width:100%" border="1">
<caption>Books and their authors</caption>
<tr>
  <th>Name</th>
  <th colspan="2">Books</th>
</tr>
<tr>
  <th rowspan="2">Shakespeare</th>
  <td>King Lear</td>
  <td>Romeo and juliet</td>
</tr>
<tr>
  <th>Chetan Bhagat</th>
  <td>3 mistakes of my life</td>
  <td>Half Girlfriend</td>
</tr>
</table>
Try It