Creating tables
During the initial years of websites, tables were the only HTML element capable of producing a simple to complex layout. These days are slowly fading with the use of CSS layouts. However, when you need the ability to display tabular data (such as an Excel spreadsheet) or creating a stable and useable form, they are still a practical choice to use. In this article, we will examine basic table markup and structure, along with ways to style tables with CSS. Finally, we’ll see how to create a simple layout using a table with CSS.
Create the page
In your text editor, create a new file and name it table.html and add the following code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>My Table</title> </head><body> <table> <tr> <td>Pet Breed</td> <td>Pet Name</td> </tr> </table>
</body> </html>
If you read Creating an HTML web page then you should be familiar with the structure, but we will review briefly:
- <table>
- Starts a table
- <tr>
- Creates and starts a new row
- <td>
- Creates and starts a table cell
- </td>
- Closes a table cell
- </tr>
- Closes a table row
- </table>
- Closes a table
From the example above, Pet Breed and Pet Name are our table contents. Save your file and preview the file.
Even though our cell contents don’t appear to be within a table, they are.
Adding a border, cell padding and cell spacing
In order to make our two cell contents to look like they reside inside a table, we need to create a border, which will surround our table. While we’re at it, we’ll add a little breathing room between our table cells and table border, along with spacing between individual cells. Add the following code:
<table border="1" cellpadding="8" cellspacing="2">
<tr>
<td>Pet Breed</td>
<td>Pet Name</td>
</tr>
</table>
Let’s examine the code in greater detail:
- Border
- Set to a value of 1, which creates a thin outline around our table
- Cell padding
- Set to a value of 8, which provides space between table cells and our table border
- Cell spacing
- Set to a value of 2, which provides spacing between individual cells
Save your file and preview the results.
Table cell border, padding and spacing
Adding table rows and centering the table
Next, let’s add two additional columns, which will hold Pet Name and age and then add the corresponding rows and cells to fill our table, along with centering our table in the browser:
<table border="1" cellpadding="8" cellspacing="2" align="center"> <tr> <td>Pet Breed</td> <td>Pet Name</td> <td>Pet Age</td> </tr> <tr> <td>Mutt</td> <td>Spike</td> <td>9</td> </tr> <tr> <td>Cocker Spaniel</td> <td>Comet</td> <td>4</td> </tr> </table>
We add align="center" which centers our table in the browser window. We also added the necessary table rows and cells. Save your file and preview the results.
Table centered and content added
We will continue the article with cell centering next.