By default, anything you place inside a table cell is aligned to the left and vertically centered. You can align the contents of table cells both horizontally and vertically with the text-align and vertical-align style properties. You can apply these attributes to any <tr>, <td>, or <th> tag. Alignment attributes assigned to a <tr> tag apply to all cells in that row. Depending on the size of your table, you can save yourself a considerable amount of time and effort by applying these attributes at the <tr> level and not in each individual <td> or <th> tag. The HTML code in Listing 11.2 uses style="vertical-align:top" to bring the text to the top of each cell. Figure 11.2 shows the result. Figure 11.2. The colspan attribute in Listing 11.2 allows the upper-left cell to span multiple columns.
Listing 11.2. Alignment, Cell Spacing, Borders, and Background Colors in Tables<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>Things to Fear</title> </head> <body> <table border="2" cellpadding="4" cellspacing="2"> <tr style="background-color:silver"> <th colspan="2">Description</th> <th>Size</th> <th>Weight</th> <th>Speed</th> </tr> <tr style="vertical-align:top"> <td><img src="/books/4/158/1/html/2/handgun.gif" alt=".38 Special"/></td> <td><h2>.38 Special</h2></td> <td>Five-inch barrel.</td> <td>Twenty ounces.</td> <td>Six rounds in four seconds.</td> </tr> <tr style="vertical-align:top"> <td><img src="/books/4/158/1/html/2/rhino.gif" alt="Rhinoceros" /></td> <td><h2>Rhinoceros</h2></td> <td>Twelve feet, horn to tail.</td> <td>Up to two tons.</td> <td>Thirty-five miles per hour in bursts.</td> </tr> <tr style="vertical-align:top"> <td><img src="/books/4/158/1/html/2/axeman.gif" alt="Broad Axe " /></td> <td><h2>Broad Axe</h2></td> <td>Thirty-inch blade.</td> <td>Twelve pounds.</td> <td>Sixty miles per hour on impact.</td> </tr> </table> </body> </html> At the top of Figure 11.2, a single cell (Description) spans two columns. This is accomplished with the colspan="2" attribute in the <th> tag for that cell. As you might guess, you can also use the rowspan attribute to create a cell that spans more than one row. Spanning is the process of forcing a cell to stretch across more than one row or column of a table. The colspan attribute causes a cell to span across multiple columns; rowspan has the same effect on rows.
|