|
|
|
|
Web Design in a Nutshell, 2nd EditionBy Jennifer Niederst2nd Edition September 2001 0-596-00196-7, Order Number: 1967 640 pages, $29.95 |
Chapter 13
TablesHTML tags for creating tables were originally developed for presenting rows and columns of tabular data, but designers quickly co-opted them as a valuable tool for controlling the layout of web pages. Tables allow you to create columns of text, hold white space between elements, and restrict the dimensions of the page's content in ways other HTML formatting tags can't.
The HTML 4.01 specification on tables is a great deal more complex than the previous 3.2 standard. It makes an effort to bring context and structure to table data as well as to provide systems for incremental display during download and display on nonvisual display agents (such as speech- and Braille-based browsers). To read what the HTML 4.01 specification has to say about tables, see the W3C's site at http://www.w3c.org/TR/html4/struct/tables.html.
Summary of Table Tags
In this section, browser support for each tag is noted to the right of the tag name. Browsers that do not support the tag are grayed out. Tag usage is indicated below the tag name. Start and end tags are required unless otherwise noted. "Deprecated" means that the tag or attribute is currently supported but is due to be phased out of the HTML specification and is discouraged from use (usually in favor of similar style sheet controls). The attributes listed for each tag reflect those in common use. A more thorough listing of attributes for each tag, according to the HTML 4.01 specification, appears in Appendix A.
<caption>
NN 2, 3, 4, 6 MSIE 2, 3, 4, 5, 5.5, 6 HTML 4.01 WebTV Opera5
<caption>...</caption>Provides a brief summary of the table's contents or purpose. The caption must immediately follow the
Attributes<table>tag and precede all other tags. The width of the caption is determined by the width of the table. The caption's position as displayed in the browser can be controlled with thealignattribute (orvalignin MSIE).
align=top|bottom|left|right- Deprecated. Positions the caption relative to the table. The default is
top.
valign=top|bottom- Internet Explorer 3.0 and higher only. Positions the caption above or below the table (
topis the default).
<col>
NN 2, 3, 4, 6 MSIE 2, 3, 4, 5, 5.5, 6 HTML 4.01 WebTV Opera5
<col>(no end tag)Specifies properties for a column (or group of columns) within a column group (
<colgroup>). Columns can share attributes (such as text alignment) without being part of a formal structural grouping.Column groups and columns were introduced by Internet Explorer 3.0 and are now proposed by the HTML 4.01 specification as a standard way to label table structure. They may also be useful in speeding table display (i.e., the columns can be displayed incrementally without waiting for the entire contents of the table).
Attributes
align=left|right|center|justify|char- Deprecated. Specifies alignment of text in the cells of a column. The default value is
left.
char=character- Specifies a character along which the cell contents will be aligned when
alignis set tochar. The default character is a decimal point (language-appropriate). This attribute is generally not supported by current browsers.
charoff=length- Specifies the offset distance to the first alignment character (
char) on each line. If a line doesn't use an alignment character, it should be horizontally shifted to end at the alignment position. This attribute is generally not supported by current browsers.
span=number- Specifies the number of columns "spanned" by the
<col>element. The default value is 1. All columns indicated in the span are formatted according to the attribute settings in<col>.
valign=top|middle|bottom|baseline- Deprecated. Specifies the vertical alignment of text in the cells of a column.
width=pixels, percentage, n*- Specifies the width of each column spanned by the
<col>element. Width can be measured in pixels or percentages, or defined as a relative size (*). For example,2*sets the column two times wider than the other columns;0*sets the column width at the minimum necessary to hold the column's contents.widthin the<col>tag overrides the width settings of the containing<colgroup>element.
<colgroup>
NN 2, 3, 4, 6 MSIE 2, 3, 4, 5, 5.5, 6 HTML 4.01 WebTV Opera5
<colgroup>...</colgroup>(end tag optional)Creates a column group, a structural division within a table that can be appointed attributes with style sheets or HTML. A table may include more than one column group. The number of columns in a group is specified either by the value of the
spanattribute or by a tally of columns<col>within the group. Its end tag is optional.Column groups and columns were introduced by Internet Explorer 3.0 and are now proposed by the HTML 4.0 specification as a standard way to label table structure. They may also be useful in speeding the table display (i.e., the columns can be displayed incrementally without waiting for the entire contents of the table).
Attributes
align=left|right|center|justify|char- Deprecated. Specifies the alignment of text in the cells of a column group. The default value is
left.
char=character- Specifies a character along which the cell contents will be aligned when
alignis set tochar. The default character is a decimal point (language-appropriate). This attribute is generally not supported by current browsers.
charoff=length- Specifies the distance to the first alignment character (
char) on each line. If a line doesn't use an alignment character, it should be horizontally shifted to end at the alignment position. This attribute is generally not supported by current browsers.
span=number- Specifies the number of columns in a column group. If
spanis not specified, the default is 1.
valign=top|middle|bottom|baseline- Deprecated. Specifies the vertical alignment of text in the cells of a column group. The default is
middle.
width=pixels, percentage, n*- Specifies a default width for each column in the current column group. Width can be measured in pixels, percentages, or defined as a relative size (
*).0*sets the column width at the minimum necessary to hold the column's contents.
<table>
NN 2, 3, 4, 6 MSIE 2, 3, 4, 5, 5.5, 6 HTML 4.01 WebTV Opera5
<table>...</table>Defines the beginning and end of a table. The end tag is required, and its omission may cause the table not to render in some browsers.
AttributesInternet Explorer only
align=left|right|center- Deprecated. Aligns the table within the text flow (same as
alignin the<img>tag). The default alignment isleft. Thecentervalue is not universally supported, so it is more reliable to center a table on a page using tags outside the table (such as<center>or<div>).
background=url- Nonstandard. Specifies a graphic image to be tiled in the background of the table. In Internet Explorer 3.0 and higher, the image tiles behind the entire table. In Netscape Navigator 4.0, the tile repeats in each individual cell (although its support is not officially documented).
bgcolor="#rrggbb"or color name- Specifies a background color for the entire table. Value is specified in hexadecimal RGB values or by color name (see Chapter 16 for more information on specifying colors in HTML).
border=number- Specifies the width (in pixels) of the border around the table and its cells. Set it to
border=0to turn the borders off completely. The default value is 1. Adding the wordborderwithout a value results in a 1-pixel border.
cellpadding=number- Sets the amount of space, in number of pixels, between the cell border and its contents. The default value is 1. For more information, see the "Space Between Cells" section in this chapter.
cellspacing=number- Sets the amount of space (in number of pixels) between table cells. The default value is 2. For more information, see the "Space Between Cells" section in this chapter.
frame=void|above|below|hsides|lhs|rhs|vsides|box|border- Tells the browser where to draw borders around the table. The values are as follows:
voidThe frame does not appear (default)
aboveTop side only
belowBottom side only
hsidesTop and bottom sides only
vsidesRight and left sides only
lhsLeft-hand side only
rhsRight-hand side only
boxAll four sides
borderAll four sides
- When the
borderattribute is set to a value greater than zero, the frame defaults toborderunless otherwise specified. This attribute was introduced by Internet Explorer 3.0 and now appears in the HTML 4.01 specification. Netscape supports this attribute in Version 6 only.
height=number, percentage- Nonstandard. Specifies the minimum height of the entire table. It can be specified in a specific number of pixels or by a percentage of the parent element.
hspace=number- Holds a number of pixels space to the left and right of a table positioned with the
alignattribute (same ashspacein the<img>tag).
rules=all|cols|groups|none|rows- Tells the browser where to draw rules within the table. Its values are as follows:
noneNo rules (default)
groupsRules appear between row groups (
thead,tfoot, andtbody) and column groups
rowsRules appear between rows only
colsRules appear between columns only
allRules appear between all rows and columns
- When the
borderattribute is set to a value greater than zero, rules default toallunless otherwise specified.
- This attribute was introduced by Internet Explorer 3.0 and now appears in the HTML 4.01 specification. Netscape supports it in Version 6 only.
summary=text- Provides a summary of the table contents for use with nonvisual browsers.
vspace=number- Holds a number of pixels space above and below table positioned with the
alignattribute (same asvspacein the<img>tag).
width=number, percentage- Specifies the width of the entire table. It can be specified in a specific number of pixels or by percentage of the parent element.
bordercolor="#rrggbb"or color name- Specifies the color of the main center portion of a table border. (Table borders are rendered using three color values to create a 3-D effect.)
bordercolorlight="#rrggbb"or color name- Specifies the color of the light shade used to render 3-D-looking table borders.
bordercolordark="#rrggbb"or color name- Specifies the color of the dark shade used to render 3-D-looking table borders.
<tbody>
NN 2, 3, 4, 6 MSIE 2, 3, 4, 5, 5.5, 6 HTML 4.01 WebTV Opera5
<tbody>...</tbody>(start and end tags optional)Defines a row or group of rows as the "body" of the table. It must contain at least one row (
<tr>)."Row group" tags (
Attributestbody,thead, andtfoot) were introduced by Internet Explorer and are part of the HTML 4.01 specification. The attributes for<tbody>are currently not supported by any commercial browser. Row groups could speed table display and provide a mechanism for scrolling the body of a table independently of its head and foot. It could also be useful for printing long tables for which the head information could be printed on each page.
align=left|center|right|justify|char- Deprecated. Specifies horizontal alignment (or justification) of cell contents. The default value is
left.
char=character- Specifies a character along which the cell contents will be aligned. The default character is a decimal point (language-appropriate). This attribute is generally not supported by current browsers.
charoff=length- Specifies the offset distance to the first alignment character (
char) on each line. If a line doesn't use an alignment character, it should be horizontally shifted to end at the alignment position. This attribute is generally not supported by current browsers.
valign=top|middle|bottom|baseline- Deprecated. Specifies vertical alignment of cell contents.
<td>
NN 2, 3, 4, 6 MSIE 2, 3, 4, 5, 5.5, 6 HTML 4.01 WebTV Opera5
<td>...</td>(end tag optional)Defines a table data cell. The end tag is not required but may prevent unpredictable table display, particularly if the cell contains images. A table cell can contain any content, including another table.
AttributesInternet Explorer only
align=left|center|right|justify|char- Deprecated. Specifies horizontal alignment (or justification) of cell contents. The default value is
left.
background=url- Specifies a graphic image to be used as a tile within the cell. Netscape's documentation does not cover this tag, but it is supported by Version 4.0.
bgcolor="#rrggbb"or color name- Specifies a color to be used in the table cell. A cell's background color overrides colors specified at the row or table levels.
colspan=number- Specifies the number of columns the current cell should span. The default value is 1. According to the HTML 4.01 specification, the value zero (0) means the current cell spans all columns from the current column to the last column in the table; in reality, however, this feature is not supported in current browsers.
height=number, percentage- Deprecated. Specifies the height of the cell in number of pixels or by a percentage value relative to the table height. The height specified in the first column will apply to the rest of the cells in the row. The height values need to be consistent for cells in a particular row. Pixel measurements are more reliable than percentages, which only work when the height of the table is specified in pixels.
nowrap- Deprecated. Disables automatic text wrapping for the current cell. Line breaks must be added with a
<br>or by starting a new paragraph. This attribute is only supported in Internet Explorer 5 and higher.
rowspan=number- Specifies the number of rows spanned by the current cell. The default value is 1. According to the HTML 4.01 specification, the value zero (0) means the current cell spans all rows from the current row to the last row; in reality, however, this feature is not supported by any browsers.
valign=top|middle|bottom|baseline- Deprecated. Specifies the vertical alignment of the text (or other elements) within the table cell. The default is
middle.
width=number- Deprecated. Specifies the width of the cell in number of pixels or by a percentage value relative to the table width. The width specified in the first row will apply to the rest of the cells in the column, and the values need to be consistent for cells in the column.
New in HTML 4.01
bordercolor="#rrggbb"or color name- Defines the border color for the cell.
bordercolorlight="#rrggbb"or color name- Defines the dark shadow color for the cell border.
bordercolordark="#rrggbb"or color name- Defines the light highlight color of the cell border.
These attributes are part of the HTML standard but are not supported by current browsers.
abbr=text- Provides an abbreviated form of the cell's content.
axis=text- Places a cell into a conceptual category, which could then be used to organize or search the table in different ways.
char=character- Specifies a character along which the cell contents will be aligned. The default character is a decimal point (language-appropriate).
charoff=length- Specifies the offset distance to the first alignment character (
char) on each line. If a line doesn't use an alignment character, it should be horizontally shifted to end at the alignment position.
headers=id reference- Lists header cells (by
id) that provide header information for the current data cell. This is intended to make tables more accessible to nonvisual browsers.
scope=row|col|rowgroup|colgroup- Specifies the table cells for which the current cell provides header information. A value of
colindicates that the current cell is the header for all the cells that fall below.colgroupindicates the current cell is the header for the column group that contains it. A value ofrowmeans that the current cell is the header for the cells in the rest of the row.rowgroupmeans the current cell is the header for the containing rowgroup. This is intended to make tables more accessible to nonvisual browsers.
<tfoot>
NN 2, 3, 4, 6 MSIE 2, 3, 4, 5, 5.5, 6 HTML 4.01 WebTV Opera5
<tfoot>...</tfoot>(end tag optional)Defines the foot of a table and should contain information about a table's columns. It is one of the "row group" tags introduced by Internet Explorer and proposed in the HTML 4.01 specification. A
<tfoot>must contain at least one row (<tr>).See
<tbody>for more information and a list of supported attributes.
<th>
NN 2, 3, 4, 6 MSIE 2, 3, 4, 5, 5.5, 6 HTML 4.01 WebTV Opera5
<th>...</th>(end tag optional)Defines a table header cell. Table header cells function the same as table data cells (
Attributes<td>). Browsers generally display the content of table header cells in bold text centered horizontally and vertically in the cell (although some browsers vary). The end tag is optional.The
<th>tag uses the same attributes as the<td>tag. See listing under<td>.
<thead>
NN 2, 3, 4, 6 MSIE 2, 3, 4, 5, 5.5, 6 HTML 4.01 WebTV Opera5
<thead>...</thead>(end tag optional)Defines the head of the table and should contain information about a table. It must contain at least one row (
<tr>).<thead>is one of the "row group" tags introduced by Internet Explorer and proposed in the HTML 4.01 specification.See
<tbody>for more information and a list of supported attributes.
<tr>
NN 2, 3, 4, 6 MSIE 2, 3, 4, 5, 5.5, 6 HTML 4.01 WebTV Opera5
<tr>...</tr>(end tag optional)Defines a row of cells within a table. A table row as delimited by
Attributes<tr>tags contains no content other than a collection of table cells (<td>). Settings made in the<tr>tag apply to all the cells in that row, but individual cell settings override those made at the row level.Internet Explorer only
align=left|center|right|justify|char- Deprecated. Aligns the text (or other elements) within the cells of the current row. This attribute has been deprecated by the HTML 4.01 specification in favor of positioning with style sheets.
bgcolor="#rrggbb"or color name- Specifies a color to be used in the row. A row's background color overrides the color specified at the table level.
char=character- Specifies a character along which the cell contents will be aligned. The default character is a decimal point (language-appropriate). This attribute is generally not supported by current browsers.
charoff=length- Specifies the offset distance to the first alignment character (
char) on each line. If a line doesn't use an alignment character, it should be horizontally shifted to end at the alignment position. This attribute is generally not supported by current browsers.
valign=top|middle|bottom|baseline- Deprecated. Specifies the vertical alignment of the text (or other elements) within cells of the current row.
background=url of image file- Specifies a graphic image to be used as a tile within the row.
bordercolor="#rrggbb"or color name- Defines the border color for the row.
bordercolorlight="#rrggbb"or color name- Defines the dark shadow color for the row border.
bordercolordark="#rrggbb"or color name- Defines the light highlight color of the row border.
Introduction to Tables
Although there are no true classifications, tables can be used in the following general ways:
Table usage
Illustration
Data Table
This is a table at its most basic (and as the creators of HTML intended)--rows and columns of textual data. Of course, data tables can be much larger and more complex than the one shown in this example.
![]()
Text Alignment
Tables are often used to clean up the display of text by creating effects common to print, such as columns, hanging indents, and extra white space. They are also useful for lining up text and input elements in forms.
![]()
Page Template
Many web designers use a large table as a container to give structure to a page. One common configuration is to create narrow columns for navigational items, as shown in this example. A template for a two-column table follows in the "Templates" section of this chapter.
![]()
Multipart Image Container
Tables can be used to hold together a large graphic that has been divided into separate sections to accommodate animations, rollovers, etc. In the example at right, the border was turned on to reveal the individual sections. Holding images together with tables is discussed at the end of this chapter.
![]()
The HTML 4.01 specification proposal discourages the use of tables for page layout, favoring Cascading Style Sheets with absolute positioning instead. But until style sheets (particularly the positioning features) are more universally and consistently supported by the browsers in current use, tables remain a designer's most reliable tool for constructing complex page layouts.
Basic Table Structure
At their most basic, tables are made up cells, arranged into rows. You can control display characteristics for the whole table, for individual rows, and for individual cells.
Rows and Cells
The bare minimum tags for describing a table are
<table>,<tr>, and<td>. The following HTML shows the basic structure for a four-cell table:<TABLE><TR><TD>cell 1</TD><TD>cell 2</TD></TR><TR><TD>cell 3</TD><TD>cell 4</TD></TR></TABLE>The
<table>tag defines the beginning and end of the table. Its contents include a number of rows (two in our simple example). Each row is defined by<tr>tags and is made up of a number of data (or header) cells. Data cells are indicated by the<td>tag. A table cell may contain any data that can be displayed in an HTML document (formatted text, images, multimedia elements, and even other tables).Figure 13-1 gives a visual representation of this concept. The image on the left shows that the table consists of two rows, each containing two cells. The image on the right shows how the HTML corresponds to the rows and cells.
Figure 13-1. HTML table structure
![]()
Header cells use the
<th>tag and function the same as data cells, but they are generally displayed in bold centered text (although some browsers vary). You may also add a caption to the table (using the<caption>tag), which provides a title or brief description of the table. The<caption>tag should be placed before the first row of the table; be sure that it is outside the row containers. Because tables are so often used as layout devices only, the caption feature is less often used than the other main table components.The table system in HTML is very row-centric. Rows are labeled explicitly, but the number of columns is just implied by the number of cells in the longest row. In other words, if all the rows have three
<td>s, then the table has three columns. If one row contains four<td>s and all the others contain two, the browser displays the table with four columns, adding blank cells to the shorter rows. HTML 4.01 includes an advanced system for describing table structure that includes explicit column tags. This system is discussed in the "Row and Column Groups" section of this chapter.One of the tricks of designing tables is understanding what aspects of the table are controlled at the table, row, and cell levels.
Table-level controls
At the table level (using attributes within the
<table>tag outlined previously), you can control:
- The width of the table and its position on the page
- The thickness of the border around the table and between cells
- The spacing within and between cells (using
cellpaddingandcellspacing, respectively)
- The background color of all its cells
Row-level controls
For each row (using attributes within the
<tr>tag), you can control only:
- The vertical and horizontal alignment of the contents of all the cells in that row
- Background colors for all the cells contained in that row. Some browsers color the row background as well as the individual cell areas.
Row settings override table-level settings. Note that table row tags are merely containers for cell tags and contain no actual data themselves.
Cell-level controls
Much of a table's structure and appearance is controlled at the individual cell level using
<td>or<th>attributes. Only the content within<td>or<th>tags is displayed in the browser. Within cells, you can control:
- The vertical and horizontal alignment of the cell's contents
- The color of the cell background
- The height and width of the cell (and the row and column that contain it)
- Whether the cell should span over more than one cell space in the table grid
Alignment and color specifications at the cell level override settings made at the row and table level.
Spanning Rows and Columns
Cells in a table can occupy the space of more than one cell in a row or column. This behavior is set within the
<th>or<td>tags using thecolspanandrowspanattributes.Column span
In Figure 13-2,
<td colspan=2>tells the browser to make "cell 1" occupy the same horizontal space as two cells ("span" over two columns). The resulting spanned cell is indicated in the figure on the left. Note that the row containing the spanned cell now only has one set of<td>tags instead of two.
Figure 13-2. The colspan attribute expands cells horizontally to the right
![]()
Setting the
colspanto a number greater than the actual number of columns (such ascolspan=4for our example) may cause some browsers to add empty columns to the table, possibly throwing your elements out of alignment. For example, in Netscape 4.5 and earlier, additional collapsed columns appear as an extra-wide border on the right of the table. The HTML 4.01 specification requests that empty cells not be added when thecolspanexceeds the number of columns.Row span
Similar to
colspan, therowspanattribute stretches a cell to occupy the space of cells in rows below. Include therowspanattribute in the row where you want the cell to begin and set its value equal to the number of rows you want it to span.In Figure 13-3, note that the bottom row now only contains one cell (the other one has been incorporated into the vertical spanned cell). The resulting spanned cell is illustrated in the figure on the left. The browser ignores overextended
rowspanvalues.
Figure 13-3. The rowspan attribute expands cells vertically
![]()
TIP: You may combine
colspanandrowspanattributes to create a cell that spans both rows and columns.Row and Column Groups
Internet Explorer 3.0 introduced a system for grouping rows and columns so they can be treated as units by style sheets or other HTML formatting tags. Row and column groups are mostly advantageous for long, complex tables containing actual data (as opposed to tables used strictly for page layout).
The system is reflected in the HTML 4.01 specification for tables, and it is now supported by Netscape 6 and other standards-compliant browsers. However, support for row and column groups is far from universal as of this writing, so keep them in mind but use them with caution. With careful coding, you can code tables with row and column groups in a way that will not disrupt display in older browsers.
The following is a brief introduction to row and column groups. For more information and examples, see the tables section of the HTML 4.01 specification (http://www.w3c.org/TR/html4/struct/tables.html). There is a useful article demonstrating the use of row and column groups at CNET's Builder.com at http://www.builder.com/Authoring/Tagmania/020700/.
Row groups
The rows in a table can be grouped into a table head (
<thead>), a table foot (<tfoot>), and one or more table bodies (<tbody>). The head and foot should contain information about the document and may someday be used to display fixed elements while the body scrolls independently. For instance, the contents of the table head and foot would print on every page of a long table that has been divided over several pages. It is recommended by the W3C that the table foot (if there is one) appear before the body of the table so the table can render the foot before downloading all the (potentially numerous) rows of data.You can use the
<tbody>tag to define row groupings and then apply style sheet information to specific groups or add rules between sections of the table using therulesattribute, for example (see "Borders, Frames, and Rules" later in this chapter).Column groups
Column groups create structural divisions within a table, explicitly identifying columns and enabling style information to be applied to all the cells within a specific column (traditionally, this would have had to be done within each individual cell). In addition, vertical rules can be added between column groups using the
rulesattribute (discussed later).The
<colgroup>tag delimits a conceptual group of columns. The number of columns included in the group is indicated with thespanattribute or by the total of<col>elements (with theirspanvalues) within the column group. Attributes in the<colgroup>element apply to every column within that group.The <
col>element is used to apply attribute specifications to an individual column or across several columns without actually grouping them together structurally or conceptually. Like<colgroup>, you can specify the span (number of affected columns) and width (in pixels, percentages, or relative values) within the<col>tag.Sample HTML
Example 13-1 is a bare-bones example of how row and column groups are integrated into the HTML table structure. Figure 13-4 shows the result.
Figure 13-4. A table using the column and row groups to organize structure
![]()
Note again that row and column groups and their attributes are not universally supported at this time and can cause display problems. For instance, a browser that supports the
<tfoot>element looks for it in the beginning of the document but knows to put its contents at the bottom of each page. In browsers that don't support this table structure, the footer information would be the second thing displayed on the page and would not be displayed again.
Example 13-1: Column and row groups <TABLE BORDER=1><CAPTION>Table Description</CAPTION><COLGROUP> A<COL span=2 width=100><COL span=1 width=50></COLGROUP><THEAD valign="top"> B<TR><TH>Heading 1</TH><TH>Heading 2</TH><TH>Heading 3</TH></TR></THEAD><TFOOT> C<TR><TD>Footer 1</TD><TD>Footer 2</TD><TD>Footer 3</TD></TR></TFOOT><TBODY> D<TR><TD>Cell Data 1</TD><TD>Cell Data 2</TD><TD>Cell Data 3</TD></TR></TBODY></TABLE>
- A
- This table has a total of three columns. The
<colgroup>element identifies the columns as part of the same structural group (there may be many column groups in a table, but for simplicity's sake, our example has just one). Within the colgroup, the first<col>element identifies two columns (span=2), each with a width of 100 pixels. The remaining<col>has a width of 50 pixels. If all the columns in the table were to be the same width, the width could have been specified in the<colgroup>element.
- B
- The
<thead>element defines a header for the table. The contents of the cells it contains may appear at the top of every page of the table.
- C
- The
<tfoot>defines a footer for the table. The cells in the footer row may appear at the bottom of every page. It should be defined before the actual contents of the table (<tbody>).
- D
- The
<tbody>element defines a number of rows that appear as the main content of the table.Affecting Table Appearance
The HTML table standard provides many tags for controlling the display of tables. Bear in mind that, as with most formatting tags, browsers have their own way of interpreting your instructions, so results may vary among browser releases and platforms. This is particularly true of tables since the standard is still being nailed down. As always, it is best to test in a variety of viewing environments.
It is important to note that some of the attributes that affect appearance (
align,valign, andbgcolor) have been deprecated by the HTML 4.01 specification in favor of achieving the same effects with style sheets. Expect the major browsers, however, to continue supporting the following methods until style sheets are universally supported.Borders, Frames, and Rules
The traditional method for adding a border around a table is the
borderattribute, which affects the display of the borders around and within the table. For more finely tuned control, the HTML separates control over the outer edge of the table (its frame) from the lines between cells within the table (rules). Let's look at all three attributes.The border attribute
By default, tables display with no borders. When the
borderattribute alone (with no value specified) is added to the<table>tag, a 1-pixel border is added around and between the cells, as shown in Figure 13-5.
Figure 13-5. Table with a 1-pixel border
![]()
You can also use the
borderattribute to specify a number value. Specifying a higher number for the border adds a thicker beveled border around the outside edges of the table, as shown in Figure 13-6. The thickness of the borders between cells (default of 2 pixels) is determined by the amount of cellspacing, described later.
Figure 13-6. Table with a 15-pixel border
![]()
Even if you don't want a table to display with a border in your final design, turning the border on during the design process can help in visualizing the table structure; it is particularly useful for debugging problematic tables. Just remember to turn it off again before uploading.
The frame attribute
The
frameattribute gives authors control over the display of a border around each of the outside edges of the table. By default, tables display with no frame (void). This attribute is supported by only the most recent browsers (Internet Explorer 5.5 and Netscape 6). The following is a list of all acceptable values forframe:
voidThe frame does not appear (default)
aboveTop side only
belowBottom side only
hsidesTop and bottom sides only
vsidesRight and left sides only
lhsLeft-hand side only
rhsRight-hand side only
boxAll four sides
borderall four sides
The rules attribute
The
rulesattribute determines which rules appear between cells within a table. One use for this attribute might be to display rules only between certain sets of columns or rows, as defined by<colgroup>or the row group tags (<thead>,<tbody>, and<tfoot>). This attribute is supported by only the most recent browsers (5.5 and 6). The following is a list of all the accepted values for the rules attribute (the default isnone):
noneNo rules (default)
groupsRules appear between row groups (
thead,tfoot, andtbody) and column groups
rowsRules appear between rows only
colsRules appear between columns only
allRules appear between all rows and columns
Positioning a Table on the Page
On current browsers (Navigator and Internet Explorer Versions 3.0 and higher), tables by default behave like paragraphs or other blocks, but they behave like images if floated to the left or right with the
alignattribute. Use thealignattribute in the <table> tag to position the table against the left or right margin and allow text to flow around it.As with images, you can specify a number of pixels to hold clear to the left and right of the table using thehspaceattribute.vspaceholds space above and below the table.The 4.0 browsers and later allow you to center a table on the page by setting the
alignattribute tocenter. Unlike left or right margin alignments, this setting does not allow text to flow around the table.Because this attribute is not universally supported, it is best to center a table using HTML tags such as
<center>or<div>outside the table.Aligning Text in Cells
By default, the text (or any element) in a data cell (
<td>) is positioned flush left and centered vertically within the available height of the cell, as shown in Figure 13-7.
Figure 13-7. Default placement of data within a cell
![]()
Table header text (
<th>) is generally displayed in bold text centered horizontally and vertically in the cell. You can override these defaults using thealignandvalignattributes at either the row or cell level.
- Row Settings
- Alignment settings specified within the
<tr>tag affect all the table cells (<td>or<th>) within that row. This makes it easy to apply alignment changes across multiple cells.
- Cell Settings
- Alignment attributes within a cell (
<td>or<th>) apply to the current cell. Cell settings override row settings. Furthermore, alignment settings within the contents of the cell (e.g.,<palign=right>) take precedence over both cell and row settings.
Horizontal alignment is specified with the
alignattribute, which takes the standardleft,right, orcentervalues. These values work the same as regular paragraph alignment. (Thealignattribute has been deprecated in favor of style sheet controls.)Vertical alignment is controlled using the
valignattribute, which can be set totop,middle(the default),bottom, orbaseline("first text line appears on a baseline common to all the cells in the row," but this setting is not as well supported).By default, the text in a cell automatically wraps to fill the allotted space. There is a
nowrapattribute which can be added within the table cell (<td>or<th>) to keep text on one line (unless broken by a<br>or<p>). Unfortunately, most browsers (except IE 5 and higher) ignore the attribute and wrap the text anyway. Whennowrapis supported, the table cell resizes wider if it needs to accommodate the line of text.Sizing Tables
You can control the size of the entire table as well as the size of rows and columns. By default, a table (and its rows and columns) are sized automatically to the minimum dimensions required to fit their contents. In many cases, it is desirable to assign a table or column a specific size (especially when using the table to build a page structure).
If the contents require a width greater than the specified size, the table generally resizes to accommodate the contents. Size specifications are treated as suggestions that will be followed as long as they don't conflict with other display directions. In effect, by specifying the size of a table you are merely specifying the minimum size. It is best to specify ample room to accommodate the contents of the cells.
Table dimensions
The
widthattribute is used within the <table> tag to specify the width of the table. You can specify an absolute value (measured in pixels) or a relative value (a percentage of the available width of the screen) as shown in the following table:
Style
Sample HTML
Result
Absolute value
<TABLE WIDTH=600>Makes the table 600 pixels wide
Relative value
<TABLE WIDTH=80%>Makes the table 80% of the screen width
To make a table fill the browser width, set the width to 100%.
Table height can be specified using the
heightattribute, which can also be defined by absolute or relative values. Theheightattribute is not part of the HTML standard, but it is well supported by browsers. If the contents of the table are longer than your specified height, the table expands to fit the contents. Therefore, theheightattribute merely specifies a minimum, not an exact height for the table.Cell dimensions
Use the
widthandheightattributes within a cell tag (<td>or<th>) to specify the dimensions of that cell. A cell's width setting affects the width of the entire column it occupies, so column widths can be specified by setting the width of just one cell in the column (generally those in the top row); the remaining cells will follow.Likewise, the cell's height may determine the height of all the cells in that row, so row height can be set using just one cell in each row.
Height and width values can be absolute measurements in pixels, or percentages relative to the dimensions of the table. Percentage heights don't work in table cells unless the height of the entire table is specified in pixels. Percentage measurements are problematic for Navigator 3.
Table Cell Spacing
There are two types of space that can be added in and around table cells: cell padding and cell spacing. The
cellpaddingandcellspacingattributes are used within the<table>tag and apply to the whole table (you can't specify padding or spacing for individual cells).
cellspacingThe amount of space between table cells is controlled by thecellspacingattribute within the<table>tag. Values are specified in number of pixels. Increasing the cell spacing results in wider shaded borders between cells. In the left image in Figure 13-8, the gray areas indicate the 10 pixels of cell spacing added between cells. The default value forcellspacingis 2; therefore, if nocellspacingis specified, browsers will automatically place 2 pixels of space between cells.
Figure 13-8. Cell spacing versus cell padding
![]()
cellpaddingCell padding refers to the amount of space between the cell's border and the contents of the cell (as indicated in Figure 13-8). It is specified using thecellpaddingattribute within the<table>tag. Values are specified in number of pixels; the default value is 1. Relative values (percentages of available space) may also be used.
- Different effects can be created using different combinations of spacing and padding. If you want your table to be seamless, as when it is holding together an image, be sure to set the border, cellspacing, and cellpadding to 0, as follows:
<TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0>
Coloring Tables
You can specify a background color for the entire table (
<table>), for selected rows (<tr>), or for individual cells (<td>or<th>) by placing thebgcolorattribute in the appropriate tag. Thebgcolorattribute is recognized by Internet Explorer Versions 2.0 and higher and Navigator Versions 3.0 and higher.Color values can be specified by either their hexadecimal RGB values or a standard color name. For more information on specifying color in HTML, see Chapter 16.
Color settings in a cell override settings made at the row level, which override settings made at the table level. To illustrate, in the following example, the whole table is set to light gray, the second row is set to medium gray, and the furthest right cell in that row is set to dark gray. Figure 13-9 shows the results.
<TABLE BORDER=1 BGCOLOR="#CCCCCC"><TR><TD></TD><TD></TD><TD></TD></TR><TR BGCOLOR="#999999"><TD></TD><TD></TD><TD BGCOLOR="#333333"></TD></TR><TR><TD></TD><TD></TD><TD></TD></TR><TR><TD></TD><TD></TD><TD></TD></TR></TABLE>
Figure 13-9. Effects of setting background colors at cell, row, and table levels
![]()
Navigator and Internet Explorer treat background colors at the table level differently. Navigator fills every cell in the table with the specified color, but the border picks up the color of the document background. IE fills the entire table area, including the borders, with the specified color for a more unified effect. When you set background colors for individual cells or rows, it will be displayed the same way on both browsers (although Navigator uses the document background color for empty cells).
Table Troubleshooting
Despite the control they offer over page layout, tables are also notorious for causing major headaches and frustrations. This is partly due to the potential complexity of the code--it's easy to miss one little character that will topple a table like a house of cards. Another source of chaos is that browsers are inconsistent and sometimes quirky in the way they interpret table code. It is not uncommon to spend several careful hours crafting a table that looks perfect in browsers X and Y but crumbles into a little heap in browser Z.
Although not every problem can be anticipated, there are a number of standard places tables tend to go wrong. HTML tables have some inherent peculiarities that can make them frustrating to work with, but knowing about the potential pitfalls up front can make the design process go more smoothly. As always, it is necessary to test your designs on as many browser and platform configurations as possible.
Calculating Table Size
In some instances, your design may require that the dimensions of a table stay fixed at a certain pixel size. Unfortunately, setting the
widthandheightattributes in the<table>tag is not a guarantee that your table will appear at that size when finally rendered. These attributes merely specify a minimum size, but the table will expand as necessary to accommodate its contents.Tables also expand according to the border, cellpadding, and cellspacing settings, as shown in Figure 13-10. In order to keep a table at its specified size, all of these attributes must be set to zero, and the contents of the cell must fit comfortably within the allotted space (or just set the table dimensions to a size that takes into account your padding and spacing values). Bear in mind, also, that contents such as text or form elements can be unpredictable and may change the size of your table as well, as discussed in the next two sections.
Figure 13-10. The effect of cellpadding, cellspacing, and border settings on table dimensions
![]()
Text in Tables
When designing tables that contain text, remember that text size can vary greatly from user to user. This adds an inherent level of unpredictability to the way your tables display.
Not only does text display larger on PCs than on Macs, each browser user can set the font size for text display. So although you've put a nice, tidy column of options in a table cell, for the user whose font is set to 16 points, the text may get some extra line breaks and change your table's dimensions.
In general, variable text sizes affect the height of cells and tables as the cells stretch longer to accommodate their larger contents (particularly if the width has been specified with an absolute pixel value). If you have HTML text in a cell, particularly if the cell needs to be displayed at specific pixel dimensions within the table, be sure to give it lots of extra room and test your page with different browser font settings.
If you are using style sheets, you can control the size of the text by setting it to a specific pixel height; bear in mind, however, that many users still use browsers that do not support style sheets. For browsers that do, your pixel settings will override the browser's font size settings, which means that you risk annoying users by forcing text to be smaller than their preferences.
Form Elements in Tables
Like text, the way form elements display in a browser is dependent on the size of the default monospace (or constant width) font that is specified in the user's browser preferences. If the user has his monospace font set to 24 points (or to "largest" in Internet Explorer), your form elements (particularly text fields) will resize larger accordingly.
In the real-world example in Figure 13-11, I used a table to hold together a badge illustration, which contained a form for entering a name and password. In testing, we found that the target audience generally had their browser fonts set to 18 points (they were working on very high-resolution monitors), which caused the form text fields to resize and break the table apart. Making the badge image larger and incorporating lots of extra space was the solution in this case.
Figure 13-11. The badge looks fine when browser fonts are set to 12 points, but falls apart at 18 points
![]()
Unwanted White Space
It is common for extra white space to creep between table cells (or between the cells and the border). When you are trying to create a seamless effect with colored cells or hold together pieces of a larger image (such as Figure 13-12), this extra space is unacceptable.
Returns and spaces within <td> tags
The problem most often lies within the cell (
<td>) tag. Some browsers render any extra space within a<td>tag, such as a character space or a line return, as white space in the table. This can occur when the cell contains text; however, the effect is most noticeable when the contents are images.TIP: Because
<table>and<tr>tags are regarded only as containers for other tags, not as containers for actual content or data, spaces and returns within these tags are ignored.If you want a seamless table, begin by setting the
border,cellpadding, andcellspacingin the<table>tag to zero (0). In the code in Figure 13-12, a graphic is divided into four parts and held together with a table. The goal is to hold the graphic together seamlessly. As shown in the figure, the returns and extra spaces within the<td>tags add white space in each cell.
Figure 13-12. Line breaks within <td> tags add white space to table cells
![]()
To keep out unwanted white space, be sure that the enclosing
<td>and</td>tags are flush against the content of the cell, with no extra spaces or returns. In Figure 13-13, I've kept the<td>tags and their contents on one line, and the problem goes away.
Figure 13-13. Removing line breaks from table cells creates a seamless table
![]()
Missing end tags
In most cases, cell end tags (
</td>) are optional, but omitting them may add extra white space to the cell, because the line break to the next starting<td>tag is rendered as extra space.The following code, in which the
</td>tags have been left out, produces extra space (as in Figure 13-12):<TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0><TR><TD><IMG SRC="bug1.gif"><TD><IMG SRC="bug2.gif"><TR><TD><IMG SRC="bug3.gif"><TD><IMG SRC="bug4.gif"></TABLE>For seamless tables, it is necessary to use end tags and keep them flush to the content, as shown in Figure 13-13.
Cellspacing in Navigator[1]
According to the HTML specification, if you set
cellspacing=0within the<table>tag, there should be no extra space between cells. There is a bug in Netscape's table implementation, however, that causes extra space to be added even when the cellspacing is set to 0. To eliminate all extra space for Netscape, you must explicitly include theborder=0attribute in the<table>tag as well.The default value of the
borderattribute should be 0, but in Netscape it takes up space (even though it doesn't draw a shaded line) unless you explicitly set it to 0. These problems have been fixed in Netscape 6.Collapsing Cells in Navigator
As of this writing, all versions of Netscape (even 6) collapse empty cells and do not render a background color in a collapsed cell. For that reason, all cells in a table need to contain something in order for it to render properly and with its background color. There are a number of options for filling cells for display in Netscape.
Nonrendering text
Sometimes, adding a simple nonbreaking space (
) or a single line break (<br>) within a cell is enough for the cell to be displayed properly in Navigator. Neither of these text strings renders visibly when the table is displayed in the browser.Be aware that a nonbreaking space occupies the height and width of a normal text character, even though nothing displays on the page. If you need to fill a very short cell with a specific pixel height, using a nonbreaking space may force the cell to be taller and throw off the dimensions of your table. Try a
<br>or a single-pixel graphic instead if your table cell dimensions are misbehaving.The single-pixel trick
Another popular work-around is to place a transparent one-pixel GIF file in the cell and set its width and height dimensions to fill the cell. If you choose this method, be sure to set both the
heightand thewidthattributes. If you set only one, many browsers will resize the image proportionally (into a big square), which may not be appropriate for the table.One drawback to this method is that a missing graphic icon will appear in the cell if the graphic doesn't load properly or if the viewer has the graphics turned off in the browser.
Using <spacer>
Table cells can also be held open with a
<spacer>tag, which is Netscape's proprietary method for adding blank space on a web page. Set the spacer type to "block" and specify the width and height measurements as follows:<TD><SPACER TYPE=block WIDTH=nHEIGHT=n></TD>Although the
<spacer>tag is Netscape-specific, the whole cell-collapsing problem is Netscape-specific as well, making spacers a good solution in this situation (although they're best avoided for general use). Browsers that don't understand the<spacer>element just ignore it, but chances are they won't need it to render the table properly anyway.Restraining Row Heights[2]
You might guess that the following code would create the table shown in Figure 13-14:
<TABLE CELLSPACING=0 CELLPADDING=0 BORDER=1><TR><TD ROWSPAN=2><IMG SRC="red.gif"WIDTH=50 HEIGHT=150></TD><TD HEIGHT=50><IMG SRC="blue.gif"WIDTH=100 HEIGHT=50></TD></TR><TR><TD ALIGN=center>extra space</TD></TR></TABLE>
Figure 13-14. This is the table we're trying to create
![]()
However, what actually happens is that the bottom cell shrinks to fit the text it contains, and the cell containing the darker graphic on the right--despite being set to
height=50--is stretched vertically, as shown in Figure 13-15.
Figure 13-15. The actual result of the code
![]()
The problem is that the
heightattribute specifies a minimum, not a maximum, and a row defaults to the height of its tallest cell (determined by either the cell's contents or its height value). That's why the table doesn't work as intended--the text in the last cell isn't tall enough to force the desired effect. Since we can determine the exact height that we want in that last cell (by subtracting the height of blue.gif from the column height), giving it aheight=100attribute will make it the proper height.If you don't know the exact height--say, because other columns contain text--you may be better off removing the
rowspanattributes and using a nested table instead (a table within a table). The nested table will size its rows based on their content only.Column Span Problems[3]
If you want to create a table with multiple column spans, yet accurately control the width of each column, it is necessary to specify a width for at least one cell in each column. When column spans overlap, it is easy to get unpredictable results.
In order to create the table shown in Figure 13-16, it seems clear that we need a table that is 600 pixels wide with three columns of 200 pixels each. In each row, there is a 400-pixel-wide graphic that should straddle neatly over two columns.
Figure 13-16. The target layout: getting two graphics to span two columns
![]()
The first (failed) attempt at coding set the table to a specific width and provided column spans for the graphics, as shown in the following code:
<TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 WIDTH=600 BGCOLOR="#FFFFFF"><TR><TD COLSPAN=2><IMG SRC="2col.gif" ALIGN=top WIDTH="400"HEIGHT="50" BORDER="0"></TD><TD ALIGN=center>width<BR>(should be 200 pixels)</TD></TR><TR><TD ALIGN=center>width<br>(should be 200 pixels)</TD><TD COLSPAN=2><IMG SRC="2col.gif" ALIGN=TOP WIDTH="400"HEIGHT="50" BORDER="0"></TD></TR></TABLE>This code, however, doesn't give the browser enough information, particularly about the width of the center column, to accurately render the table. The unsuccessful result of this first code attempt is shown in Figure 13-17. The problem is that the center column is not defined anywhere.
Figure 13-17. Since the middle column was not defined, the table is rendered with two 400-pixel-wide columns
![]()
The solution
The solution in this case, because the middle cell is eaten up by column spans in both rows, is to create a dummy row (shown in bold) that specifies an absolute width for all three columns as intended (200-pixels each). This row will not render in the browser because its height is set to 0, but it is enough to tell the browser what to do. Use this dummy row method when you have a table without any rows with all its cells intact.
The following code produces the desired effect on all browsers that support tables--and on all platforms.
<TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 WIDTH=600 BGCOLOR="#FFFFFF"><TR><TD WIDTH="200" HEIGHT="0"></TD><TD WIDTH="200" HEIGHT="0"></TD><TD WIDTH="200" HEIGHT="0"></TD></TR><TR><TD colspan=2 WIDTH="400"><IMG SRC="2col.gif" WIDTH="400"HEIGHT="50" BORDER="0"></TD><TD WIDTH="200" ALIGN=CENTER>width<BR>(should be 200pixels)</TD></TR><TR><TD WIDTH="200" ALIGN=center>width<br>(should be 200pixels)</TD><TD colspan=2 WIDTH="400"><IMG SRC="2col.gif" WIDTH="400"HEIGHT="50" BORDER="0"></TD></TR></TABLE>Tips and Tricks
This section provides a few tricks of the trade for working with tables.
<font> and Tables
Unfortunately, placing
<font>tags around a table will not affect the font of all the text contained within the table. You need to repeat the<font>tag and its attributes around the content in every cell of the table. For complex tables with lots of cells, the repetitive<font>tags can actually add significantly to the size of the HTML file (not to mention the visual clutter).Cascading style sheets are the proper and much more efficient way to apply style information to the contents of a table. They result in smaller files and make life much easier when you need to make changes to the design.
Waiting for Tables to Display
Using the basic table tags, the browser must wait until the entire contents of a table have downloaded before it can begin rendering the page. Any text and graphics outside the table display quickly while the browser works on the table.
You can use this phenomenon to your advantage by placing elements you want your viewers to see first outside the table (can anybody say "banner ads"?).
Note that careful use of row and column groups can give the browser enough information to display the contents of the table incrementally, before all the data has downloaded.
Baseline Alignment Trick[4]
If you want to align the first lines of text by their baselines across a row, you should be able to use
valign=baseline; in reality, this setting is too unpredictable across browsers to be used reliably. A trick for achieving the same result is to add to each first line a nonbreaking space ( ) that is set the same size as the largest character. That way, you can setvalign=top, and the baselines will all line up.First look at simple top alignment. As shown in Figure 13-18, the top of the text is aligned, but the baselines are off. By adding a nonbreaking space at the larger text size (in bold), the baselines align neatly, as shown in Figure 13-19.
Figure 13-18. With top alignment, the baselines of the text don't line up
![]()
Figure 13-19. With a nonbreaking space set at the same font size as the "Man" text, the baselines line up
![]()
Rowspans Made Easy[5]
HTML 3.2 specifies that if a cell's
colspanimplies more columns than have been created up to that point in the table, the browser should create the additional columns. Withrowspan, however, the specification states that browsers shouldn't create any extra rows. The existing browsers follow both these rules.So if you have a cell that spans vertically to the bottom of the table, past rows that might vary in number or are too numerous to easily count, just give it a
rowspanthat you know is excessively high.In Figure 13-20, we've set
rowspanto 99. Even though there are only seven rows in the actual table, browsers won't generate any extra rows.
Figure 13-20. Although rowspan is set to 99, the table only contains the actual number of rows needed
![]()
Standard Table Templates
Ever look at a table and wonder, "How'd they do that?" This section provides templates that give you shortcuts for creating standard table effects.
A Simple Announcement Box
Figure 13-21 depicts a simple one-cell table containing text. By setting the background to a bright color, it can be used as an effective attention-getting device for a special announcement. It could also be used as an alternative to a graphical headline for a page. By using the
alignattribute in the<table>tag, you can position the table along the left or right margin and allow text to wrap around it, making a nice space for a sidebar or callout.You can use
widthandheightattributes to make the bar any size. Try playing with the border and cell padding for different effects. Remember, placing thebgcolorwithin the cell will render differently than placing it in the<table>tag in Internet Explorer, so experiment and test to see what you like the best. Note that becauseheightis a nonstandard attribute, it may not work in all browsers (including Version 6 browsers operating in "strict" rendering mode).
Figure 13-21. Announcement box
![]()
Centering an Object in the Browser Window
The table in the following code can be used to center an object in a browser window regardless of how the window is resized (as shown in Figure 13-22). It uses a single cell table with its size set to 100%, then centers the object horizontally and vertically in the cell.
<HTML><BODY><TABLE WIDTH=100% HEIGHT=100% BORDER=0 CELLSPACING=0 CELLPADDING=0><TR><TD align=center valign=middle>your object here</TD></TR></TABLE></BODY></HTML>
Figure 13-22. Centering an object
![]()
Creating a Vertical Rule
This sample table creates a vertical rule between columns that resizes with the height of the table. The trick is to create an extra column only one pixel wide (or the desired thickness of the vertical rule) and fill it with a background color. This cell is indicated in bold. The result is shown in Figure 13-23.
The cell cannot be totally empty or it will collapse in Navigator and its background color won't display, so I've added a
<br>. For this to display correctly, the cell padding must remain at zero, or the 1-pixel wide column will plump up with extra space. Add space between columns with thecellspacingattribute instead.
Figure 13-23. A vertical rule that resizes with the depth of the table
![]()
Creating a Box Rule
Although Microsoft Internet Explorer recognizes the proprietary
bordercolor,bordercolorlight, andbordercolordarkattributes, there is no method for specifying border colors using standard HTML for all browsers.To create a colored rule around a box of text using standard HTML, place one table within another as shown in Figure 13-24. To nest tables, place the entire contents of one table within a
<td>of the other.
Figure 13-24. Two examples of creating box rules with nested tables
![]()
In Example 1 in Figure 13-24, cell width and height are set in the interior table. In the exterior table, a cell padding of 0 results in a one-pixel rule around the table. You can increase the thickness of the rule by increasing the
cellpaddingvalue. Note, however, that this will also increase the overall dimensions of the table. The color of the rule is specified by thebgcolorattribute in the<table>tag for the exterior table:<TABLE CELLPADDING=0 BORDER=0><TR><TD BGCOLOR="#333333" ALIGN=center VALIGN=center><TABLE BORDER=0 WIDTH=200 HEIGHT=200 CELLPADDING=10><TR><TD BGCOLOR="#999999">cell contents</TD></TR></TABLE></TD></TR></TABLE>In Example 2 in Figure 13-24, to restrict the dimensions of the table, set specific dimensions for the exterior table and set the dimensions of the interior table slightly smaller (to a difference twice the desired rule thickness). In this example, the desired rule thickness is 10, so the interior table's dimensions are 20 pixels less than the exterior table's dimensions.
<TABLE WIDTH=200 HEIGHT=200 cellpadding=0 border=0><TR><TD BGCOLOR="#333333" ALIGN=center VALIGN=center><TABLE BORDER=0 WIDTH=180 HEIGHT=180 CELLPADDING=10><TR><TD BGCOLOR="#999999">cell contents</TD></TR></TABLE></TD></TR></TABLE>Two-Column Page Layouts
Many sites use a two-column table to lay out the structure of their pages. This grid creates a narrow column on the left for navigational options and a wider column on the right for the page's contents, as shown in Figure 13-25. These sample tables can be used to provide a basic structure to the page; you can place any elements (including other tables) within either table cell to create more complex layouts.
Figure 13-25. Typical two-column layout
![]()
First, a word about browser margins
When using a table to lay out the structure of a page, bear in mind that it will be placed in the page against the normal browser margins, not flush against the top and left edge of the browser window. The width of the margin varies from browser to browser (and platform to platform), but it generally ranges from 8 to 12 pixels. You should take this blank space into account when choosing measurements for your table and its column widths.
Getting rid of the browser margins for both Netscape Navigator and Microsoft Internet Explorer requires using redundant margin attributes in the
<body>tag as shown here:<BODY MARGINWIDTH=0 MARGINHEIGHT=0 LEFTMARGIN=0 TOPMARGIN=0>If you are using style sheets, add the following rule:
BODY { margin:0; padding:0;}Fixed-width columns
If it's predictability and control you're after, fixing the width of your table and its columns is the way to go. As long as the contents fit in the cells entirely, the table will hold its dimensions regardless of browser window size. If contents (such as graphics) are wider than the cell, the cell will usually expand to accommodate them.
Of course, you can change the specific width values to any pixel value you choose, but it is important that the total of the cell widths equals the width set for the entire table. If the values are different, browsers maintain the width setting for the table and resize all the columns proportionately within the allotted space. As a result, none of the column widths will display at the number of pixels you specified.
Note that the border in each of the following examples has been set to 1, but you can change it to any other value. Starting with the border set to 1 (as shown in Figure 13-25) makes it easier to see how the table is behaving. Once you get the table working properly, get rid of the border by setting the value to 0.
<HTML><BODY><TABLE BORDER=1 WIDTH=600><TR><TD VALIGN=top WIDTH=150>left column</TD><TD VALIGN=top WIDTH=450>right column</TD></TR></TABLE></BODY></HTML>Relative column widths
Using relative values for the width of your table allows your page to resize itself to fill the width of the browser window. Many designers prefer this method because it is more flexible and suits any monitor configuration. Although the actual column widths will change when the browser window resizes (and their contents will rewrap), they will remain in proportion to one another.
Again, you can turn the border off by setting the value to zero. You may change the width values for the cell in each column, but be sure that they total 100%.
<HTML><BODY><TABLE BORDER=1 WIDTH=100%><TR><TD VALIGN=top WIDTH=20%>left column</TD><TD VALIGN=top WIDTH=80%>right column</TD></TR></TABLE></BODY></HTML>Combination
At times, you may want to restrict the width of the left column but allow the right column to resize with the page--if you want the contents of the left column to stay aligned over a colored background image, for instance. Set the width of the left column to any pixel value you choose and do not specify a width for the right column.
This technique is not guaranteed to keep the width of the "fixed" column at its specified width. If the browser window is resized to be very narrow, the fixed column will be resized smaller and its contents will wrap.
<HTML><BODY><TABLE BORDER=1 WIDTH=100%><TR><TD VALIGN=top WIDTH=150>left column</TD><TD VALIGN=top>right column</TD></TR></TABLE></BODY></HTML>The trick for maintaining a minimum width for a column is to place a graphic element in a cell that is sized to the desired column width. Some developers use a 1-pixel square graphic that is stretched using the
widthattribute.Multipart Images in Tables
There are a number of reasons why you may want to slice a large image into pieces and use a table to reconstruct it seamlessly on a web page:
- Rollovers
- If you want portions of the image--but not the whole image--to respond to the mouse passing over them (mouseover events or rollovers), it is more efficient to swap out just the bits that change instead of replacing the whole image. Rollover effects are created with JavaScript. See Chapter 28 for sample code.
- Animations
- Similarly, if you want to add animation to small areas within an image, it is better to break up the image and animate just the portions that move. This will result in smaller files to download.
- Better Optimization
- At times, you may find that an image contains distinct areas of flat color and distinct areas of soft or photographic images. Breaking the image into sections allows you to save some sections as GIF (the flat color areas) and others as JPEG (for graduated tones), to achieve better optimization and image quality overall. For more information on optimizing images, see Chapters and .
- Imagemaps
- Break the image into separated linked images instead of using an imagemap. This allows alternative text (using the
altattribute) to be added for each linked section of the image (instead of a singlealtmessage for the whole imagemap). This makes the page more accessible for people using non-graphical or speech-based browsers.
In Figure 13-26, I've divided an image into sections so I can save the television image as a JPEG and the rest as GIFs (since they are flat, graphical images). It also allows me to swap out the television image based on rollovers elsewhere on the page. The table on the right has its border set to 1 to reveal the individual graphics that make up the image. When the border is set to zero, the effect is seamless, as shown on the left.
Figure 13-26. A multipart image held together by a table
![]()
Slicing and Dicing Tools
Multipart images in tables have been growing in popularity in recent years. Not surprisingly, software companies have responded with tools that make the production process much easier than the previously discussed method of splitting the graphic manually and writing the table code in an HTML editor. (This manual method is outlined a little later.)
Macromedia Fireworks, Adobe Photoshop 6.0, and Adobe ImageReady (all available for both Windows and Mac) include functions that slice up an image, export the individually numbered graphics (based on the position of guidelines), and automatically write the table code that holds them all together.
You can then just copy and paste the table code into your HTML file. One caution: you will need to adjust the pathnames if your graphics are to reside in a different directory from your HTML files. The automatically generated code writes relative pathnames assuming everything will be in the same directory. A simple find-and-replace in your HTML file should take care of this quickly.
Macromedia Fireworks
Fireworks makes its slicing tool available in the Toolbox. These are the basic steps for creating a sliced image and its accompanying HTML file:
- Create or open your image. Using the Slice tool from the Toolbox palette, define rectangular segments of the image. Note that if you place a rectangular slice in the middle of a graphic, Fireworks automatically slices the remainder of the image into the fewest number of segments to contain the specified slice.
- To set the default export settings (file format, bit depth, color palette, dithering, etc.) for the entire image, you must be sure that no slicing objects are selected, then adjust the settings in the Optimize palette. These settings will be applied to all slices after exporting.
- You can override the default export settings for an individual slice--for instance, to reduce its palette, or to make it a different file format. Select the slice object, then adjust its properties in the Optimize palette (the word "slice" appears in the top bar when a slice is selected).
- Once you have your slices chosen and configured, export the file by selecting File
Export. In the Export dialog box, select "Use Slice Objects" from the Slicing pop-up menu and set a base name for the graphics (Fireworks names them automatically based on the name you provide). You can also set a target directory for the files.
- When you click Export, Fireworks creates all the graphic files and the HTML file for the sliced image. You can now copy the table code from the generated HTML file and paste it into your final document (be sure that the pathnames are correct).
For more information about Fireworks, see http://www.macromedia.com/software/fireworks.
Adobe ImageReady
ImageReady is a tool for advanced web graphics production that comes bundled with Photoshop Versions 5.5 and higher. The process for creating a sliced image in ImageReady is nearly the same as the one described for Fireworks.
- Open the source image. Select Slices
Show Slices to make the Slices layer visible. You may also want to use guidelines to help control your selections. Use the Slice tool (it looks like a little knife) to outline the important elements in your design. When a slice is selected, its image appears in the Slice palette.
- With the Slices layer turned off, you can use the Optimize palette to make export settings (file format, number of colors, etc.) for the entire image. You can override these settings for a particular slice by selecting it with the Slice Selection tool, then making adjustments in the Optimize palette.
- When you are ready, save the file using File
Save Optimized. This gives you a dialog box where you can choose to have ImageReady save the images and the HTML file. Click the Options buttons next to each selection to access other relative options. For an explanation of these options, see the ImageReady manual. When you are ready, click Save.
Adobe Photoshop 6
Photoshop 6 is the first Photoshop release to feature slicing functions (slicing was delegated to ImageReady in previous versions). As with ImageReady, you can create slices using a special slicing tool from the toolbar. Adobe calls slices created with the slicing tool "user-slices." Photoshop will also generate slices based on pixel information in a layer (called "layer-slices").
This is particularly useful for making rollover buttons. Place the rollover element on a separate layer and create a slice from that layer (select "New Layer Based Slice" from the Layer menu). If you apply an effect to the layer that changes the pixel dimensions (such as a glow or a drop shadow), the layer-slice automatically resizes to encompass the new pixels.
Producing Images in Tables Manually
If you do not have Fireworks or the latest version of Photoshop, it is certainly possible to create the effect by hand. First you need to divide the image into separate graphic files using an image processor such as Paint Shop Pro or Photoshop 4 (used in the following example). Photoshop 5.5 and higher comes with a copy of ImageReady that will do the work for you. Then write the HTML for the table using whichever HTML editor you like. These methods are demonstrated in the following sections.
Dividing the image (in Photoshop 4.0)
When dividing an image with Photoshop, it is important to set the guide preferences in a way that enables easy and accurate selections without redundant or overlapping pixels between image sections. This is described in steps 2 and 3.
- Open the image in Photoshop. Make sure the rulers are visible by selecting View
Show Rulers.
- Set your preferences to use pixels as the unit of measurement by selecting File
Preferences
Units & Rulers. Select "pixels" from the pop-up menu and hit OK.
- Select View
Snap to Guides. This will snap your selection to the precise location of the guide.
- Use the rectangle marquee (make sure feathering and anti-aliasing options are turned off) to select each area of the image (Figure 13-27). You can use the Info palette (Window
Show Info) to get accurate pixel measurements for each section as you select it. You'll need this information when you create the HTML file.
- Copy and paste each section into a new file (Figure 13-27). Flatten the image and save it as a GIF or JPEG. You may want to develop a numbered naming scheme to keep the pieces organized.
Figure 13-27. Splitting up an image with Photoshop
![]()
Creating the table in HTML
Following is the HTML code that is used to hold together the image from Figures 13-26 and 13-27:
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="0" WIDTH="333"><TR><TD><IMG SRC="part_1.gif" WIDTH="56" HEIGHT="92" BORDER="0"></TD><TD><IMG SRC="part_2.gif" WIDTH="169" HEIGHT="92" BORDER="0"></TD><TD><IMG SRC="part_3.gif" WIDTH="108" HEIGHT="92" BORDER="0"></TD></TR><TR><TD><IMG SRC="part_4.gif" WIDTH="56" HEIGHT="133" BORDER="0"></TD><TD><IMG SRC="part_5.gif" WIDTH="169" HEIGHT="133" BORDER="0"></TD><TD><IMG SRC="part_6.gif" WIDTH="108" HEIGHT="133" BORDER="0"></TD></TR><TR><TD><IMG SRC="part_7.gif" WIDTH="56" HEIGHT="82" BORDER="0"></TD><TD><IMG SRC="part_8.gif" WIDTH="169" HEIGHT="82" BORDER="0"></TD><TD><IMG SRC="part_9.gif" WIDTH="108" HEIGHT="82" BORDER="0"></TD></TR></TABLE>There is no difference between writing a table for piecing together graphics and writing any other kind of table; however, you should pay careful attention to the following settings if you want the image to piece back together seamlessly on all browsers.
- In the
<table>tag, set the following attributes to zero:border=0,cellpadding=0,cellspacing=0.
- In the
<table>tag, specify the width of the table with an absolute pixel value. Be sure that the value is exactly the total of the widths of the component images. You may also add theheightattribute for thoroughness' sake, but it is not required.
- Don't put extra spaces or line returns between the
<td>and the<img>tags (extra space within<td>s causes extra space to appear when the image is rendered). Keep them flush together on one line. If you must break the line, break it somewhere within the<img>tag.
- Set the
widthandheightvalues in pixels for every image. Be sure that the measurements are accurate.
- Set
border=0for every image.
- Specify the
widthandheightpixel values for every cell in the table, particularly if it containscolspansandrowspans. Be sure that they match the pixel values set in the<img>tag and the actual pixel dimensions of the graphic. For simple grid-like tables (such as the one in Figure 13-26), you may not need to give individual cell dimensions because the enclosed images will force each cell to the proper dimensions.
- If your table has a lot of column spans, be sure there is at least one row with all its cells intact so you can declare the width of every column in the table. If there are no intact rows, add a dummy row (as described in "Column Span Problems" earlier in this chapter) to ensure the image segments line up correctly.
- Sometimes it is preferable to keep the table simple. For instance, the sample graphic could have been divided into just five portions (a top graphic, three middle graphics, and a bottom graphic) and held together with a table made up of three rows with a single cell each. These decisions are a matter of judgment and obviously depend on the individual project.
1. This tip taken with permission from Creative HTML Design, by Lynda Weinman and William Weinman, published by New Riders Publishing, 1998.
2. This tip courtesy of Builder.com. It first appeared in the Builder.com article "Advanced HTML Tips," by Paul Anderson. It is reprinted here with permission of Builder.com and CNET. See http://builder.com/Authoring/AdvHtml/index.html for the complete article.
3. This tip is courtesy of Builder.com and appeared in the Builder.com article "Advanced HTML Tips," by Paul Anderson. It is reprinted here with permission of Builder.com and CNET. See http://builder.com/Authoring/AdvHtml/index.html for the complete article. The solution shown here was submitted by Steven Masters.
4. This tip courtesy of Builder.com and first appeared in the Builder.com article "Advanced HTML Tips," by Paul Anderson. It is reprinted here with permission of Builder.com and CNET. See http://builder.com/Authoring/AdvHtml/index.html for the complete article.
5. This tip courtesy of Builder.com and first appeared in the Builder.com article "Advanced HTML Tips," by Paul Anderson. It is reprinted here with permission of Builder.com and CNET. See http://builder.com/Authoring/AdvHtml/index.html for the complete article.
Back to: Web Design in a Nutshell, 2nd Edition
© 2001, O'Reilly & Associates, Inc.
webmaster@oreilly.com