HTML tables

One of the most common things done with HTML is showing a table with data. Wikipedia, for example, is full of tables like this.

You create them using the <table> tag.

Rows with TR, cells with TD

Tables consist of rows, which are placed between <tr> elements. The rows in turn contain table cells between <td> tags.

So, here is a basic table to list pizza prices:

<table>
<tr>
<td>Pizza Margherita</td>
<td>7.00$</td>
</tr>
<tr>
<td>Pizza Quatro Staggioni</td>
<td>9.00$</td>
</tr>
<tr>
<td>Pizza Mozzarella</td>
<td>8.00$</td>
</tr>
</table>

Here is how that looks in the browser:

Screen Shot 2014-01-19 at 21.00.20

Table head, body and label cells

Typically, a table also contains labels, to indicate what the data means. These are indicated with the <th> tag.

To indicate that one or more rows contain headers, you can wrap them in <thead> tags. Accordingly, the data itself is typically wrapped in <tbody> tags.

So let’s make our table a bit more advanced, with a header row on top, and the pizza names as labels.

This is the code:

<table>
<thead>
<tr><th>Pizza name</th><th>Main ingredients</th><th>Price</th></tr>
</thead>
<tbody>
<tr>
<th>Pizza Margherita</th>
<td>Cheese, tomato</td>
<td>7.00$</td>
</tr>
<tr>
<th>Pizza Quatro Staggioni</th>
<td>Ricotta,Mozarrella,Gorgonzola,Parmesan</td>
<td>9.00$</td>
</tr>
<tr>
<th>Pizza Mozzarella</th>
<td>Mozarella</td>
<td>8.00$</td>
</tr>
</tbody>
</table>

And this is how it looks:

Screen Shot 2014-01-19 at 21.19.54

Note that we applied some magic called ‘CSS’ to give background colors to the thead and td elements. If you want your table to look like the screenshot, include the following <style> declaration in your HTML code:

<style>
thead th { background-color:#888;color:#fff;}
th {background-color:#ddd;}
th, td {padding:3px;}
</style>

Are you tired of all these HTML tags by now? No? You should seriously rethink your life then, because HTML elements are boring. This is why we will start bringing them to life in our next lesson about, you guessed it, CSS!

Advertisements

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s