HTML Chapter 4 2018-12-19T12:33:25+00:00

HTML Chapter 4

Topics:- (Introducing Tables, Basic Table Elements and Attributes, Adding a <caption> to a Table, Grouping Sections of a Table, Nested Tables, Accessible Tables)

Tables

Tables display information in rows and columns; they are commonly used to display all manner of data that fits in a grid such as train schedules, television listings, financial reports, and sports results. In this chapter, you learn when to use tables, and the markup that you need to create them. To begin this chapter, we’ll look at some examples of tables, then quickly move onto the basic elements that are used to create them. Having learned the basics, you can then go on to learn some of the more advanced features of tables such as adding captions and headings, and how to achieve more complicated table layouts. Along the way, you will also learn some deprecated markup that was designed to control the appearance of tables because, even though it is preferable to use CSS to control the way a page looks, you may sometimes come across pages that use the older markup. The chapter ends with a discussion of accessibility issues that relate to tables, because it is important to understand how a screen reader would read the contents of a table to users with visual impairments.

Introducing Tables

In order to work with tables, you need to start thinking in grids, so let’s start off by looking at some examples of how popular web sites use tables. In Figure 4-1 you can see the NFL web site. This page shows the standings for each team in a table. You can see a list of teams down the left, and for each team there are columns providing different stats, including number of games won, lost, or tied.

Figure 4-1

Figure 4-2 shows the Bloomberg web site. This page shows major stock markets. In this case, there are tables for different regions around the world (in this screenshot, you can see North and Latin America as

Figure 4-2

the first region, followed by Europe, Africa, and the Middle East). Each table contains the major indexes trading in that region down the left-hand side, followed by columns that show the current value, fluctuations in values, and date/time of the stats.

In Figure 4-3 you can see the web site for the Heathrow Express, a train between Central London and London’s Heathrow Airport. The tables on this page show the times that the trains run.

Figure 4-3

In Figure 4-4, you can see the New York Times web site. On this page, the tables provide television listings.

Figure 4-4

Hope these examples give you a better idea of what a table is and when you might want to use one. We are not suggesting that every web site that displays stock market data or television listings should use a table — rather that you should consider using a table when you need to display information that sits well in a grid of rows and columns. If you are looking at a web page and want to know whether that page is using a table to control how the data is laid out, you can always look at the source for that page and look for the elements you are about to read about in this chapter.You can think of a table as being very similar to a spreadsheet because it is made up of rows and columns, as shown in Figure 4-5.

Figure 4-5

Here you can see a grid of rectangles. Each rectangle is known as a cell. A row is made up of a set of cells on the same line from left to right, and a column is made up of a line of cells going from top to bottom. Let’s look at an example of a very basic XHTML table so that you can see how they are created (see Figure 4-6).

Figure 4-6

You create a table in XHTML using the <table> element. Inside the <table> element, the table is written out row by row. A row is contained inside a <tr> element — which stands for table row. Each cell is then written inside the row element using a <td> element — which stands for table dataHere is the code that was used to create this basic table :

<table border=”1”>

<tr>

<td>Row 1, Column 1</td>

<td>Row 1, Column 2</td>

</tr>

<tr>

<td>Row 2, Column 1</td>

<td>Row 2, Column 2</td>

</tr>

</table>

When writing code for a table in a text editor, always be extra careful to start each row and cell on a new line and to indent table cells inside table rows as shown. If you are using a web page authoring tool such as Dreamweaver, it will probably automatically indent the code for you.Many web page authors find it particularly helpful to indent the code for a table because leaving off just one tag in a table can prevent the entire table from being displayed properly. Indenting the code makes it easier to keep track of the opening and closing of each element.Take a look at the same code again. This time, it has not been split onto separate lines or indented, and I’m sure you will agree it’s much harder to read.

<table border=”1”><tr><td>Row 1, Column 1</td><td>Row 1, Column 2</td></tr><tr> <td>Row 2, Column 1</td><td>Row 2, Column 2</td></tr></table>

All tables will follow this basic structure, although there are additional elements and attributes that allow you to control the presentation of tables. If a row or column should contain a heading, a <th> element should be used in place of the <td> element for the cells that contain a heading. By default, most browsers render the content of a <th > element in bold text.

Each cell must be represented by either a <td> or a <th> element in order for the table to display correctly, even if there is no data in that cell.

Let’s take a look at a slightly more complicated table (see Figure 4-7). This time the table includes headings. In this example, the table shows a financial summary for a small company.

Figure 4-7

Here is the code that was used to create this table :

<table border=”1”>

<tr>

<td></td>

<th>Outgoings ($)</th>

<th>Receipts ($)</th>

<th>Profit ($)</th>

</tr>

<tr>

<th>Quarter 1 (Jan-Mar)</th>

<td>11200.00</td>

<td>21800.00</td>

<td><b>10600.00</b></td>

</tr>

<tr>

<th>Quarter 2 (Apr-Jun)</th>

<td>11700.00</td>

<td>22500.00</td>

<td><b>10800.00</b></td>

</tr>

<tr>

<th>Quarter 3 (Jul – Sep)</th>

<td>11650.00</td>

<td>22100.00</td>

<td><b>10450.00</b></td>

</tr>

<tr>

<th>Quarter 4 (Oct – Dec)</th>

<td>11850.00</td>

<td>22900.00</td>

<td><b>11050.00</b></td>

</tr>

</table>

The first row is made entirely of headings for outgoings, receipts, and profit. Note how the top-left cell in Figure 4-7 is empty; in the code for the table, we still need an empty <td> element to tell the browser that this cell is empty (otherwise it has no way of knowing that there is an empty cell here).In each row, the first cell is also a table heading cell (indicated using a <th>), which states which quarter the results are for. Then the remaining three cells of each row contain table data and are contained inside the <td> elements.

The figures showing the profit (in the right-hand column) are contained within a <b> element, which shows the profit figures in a bold typeface. This demonstrates how any cell can, in fact, contain all manner of markup. The only constraint on placing markup inside a table is that it must nest within the table cell element (be that a <td> or a <th> element). You cannot have an opening tag for an element inside a table cell and a closing tag outside that cell — or vice versa.When creating tables, many people do not actually bother with the <th > element and instead use the <td> element for every cell — including headers. You should, however, aim to use the <th> element whenever you have a table heading.

As you can see from the examples so far in this chapter, tables can take up a lot of space and make a doc-ument longer, but clear formatting of tables makes it much easier to see what is going on in your code. No matter how familiar the code looks when you write it, you will be glad that you made good use of structure if you have to come back to it a year later.

Basic Table Elements and Attributes

Now that you’ve seen how basic tables work, this section describes the elements in a little more detail, introducing the attributes they can carry. Some of the attributes allow you to create more sophisticated table layouts. Feel free to skim through this section fairly quickly; once you know what is possible to do with the markup, you can always come back again and study the markup more closely in order to see how to achieve what you want.

The <table> Element Creates a Table

The <table> element is the containing element for all tables. It can carry the following attributes:

      All the universal attributes

      Basic event attributes for scripting

The <table> element can carry the following deprecated attributes. Even though they are deprecated, you will still see many of them in use today:

align bgcolor border cellpadding cellspacing dir frame rules summary width

The align Attribute (Deprecated)

Although it is deprecated, the align attribute is still frequently used with tables. When used with the <table> element, it indicates whether the table should be aligned to the left (the default), right, or center of the page. (When used with cells, as you will see shortly, it aligns the content of that cell.) You use the attribute like so:

<table align=”center”>

You can put a whole table inside a single cell of another table (or inside other block-level elements), and if a table is contained within another element, the align attribute will indicate whether the table should be aligned to the left, right, or center of that element. When the align attribute is used on a table, text should flow around it (rather like it can flow around an image). For example, here is a left-aligned table that is followed by some text:

<table border=”1” align=”left”>

<tr>

<td>Row 1, Column 1</td>

<td>Row 1, Column 2</td>

</tr>

<tr>

<td>Row 2, Column 1</td>

<td>Row 2, Column 2</td>

</tr>

</table>

Lorem ipsum dolor sit amet, consectetuer adipiscing elit…

The text should flow around the table, as shown in the first table in Figure 4-8.

Figure 4-8

If you do not want the text to flow around the table, you can use the CSS clear property on the element after it . Alternatively, you could place a line break after the table and add the clear attribute, which is also deprecated <br clear=”left” /> (although the CSS clear property would be the preferred method). This is demonstrated in the second table of Figure 4-8.

</table>

<br clear=”left” />

Lorem ipsum dolor sit amet, consectetuer adipiscing elit…

The clear attribute indicates how the browser should display the next line after the line break. With the value of left, the text can begin only when there is nothing positioned on the left margin of the browser window (or containing element).

The bgcolor Attribute (Deprecated)

The bgcolor attribute sets the background color for the table. The value of this attribute should either be a color name or a six-digit code known as a hex code. (The bgcolor attribute has been replaced by the background-color property in CSS.)

The syntax is as follows:

bgcolor=”red”

The border Attribute (Deprecated)

If you use the border attribute, a border will be created around both the table and each individual cell. The value for this attribute is the width you want the outside border of the table to be, in pixels. If you give this attribute a value of 0, or if you do not use this attribute, then you should not get any borders on either the table or any cells. (This has been replaced by the border property in CSS.)

border=”0”

While this attribute is deprecated, it has been used in several of the examples in this chapter so that you can clearly see where the edge of each table cell is.

The cellpadding Attribute (Deprecated)

The cellpadding attribute is used to create a gap between the edges of a cell and its contents. The value for this attribute determines the amount of space or padding inside each wall of the cell, specified either in pixels or as a percentage value (where the percentage is a percentage of the width of each cell).

cellpadding=”5” or cellpadding=”2%”

As you can imagine, if two table cells sat next to each other and both contained writing, there could be a problem. If there were not a gap between the edge of the cells and the writing, the words would butt up against each other, making them hard to read. Similarly, if there were a border around each cell and the text touched the border, it could be hard to read. Therefore, adding padding to cells makes their contents easier to read.This attribute has been replaced by the padding property in CSS.

The cellspacing Attribute (Deprecated)

The cellspacing attribute is used to create a space between the borders of each cell. The value for this attribute can be either the amount of space you want to create between the cells, in pixels, or a percentage value.

cellspacing=”6” or cellspacing=”2%”

This attribute has been replaced by the margin property in CSS.

The dir Attribute

The dir attribute is supposed to indicate the direction of text that is used in the table. Possible values are ltr for left to right text and rtl for right to left (for languages such as Hebrew and Arabic):

dir=”rtl”

If you use the dir attribute with a value of rtl on the <table> element, then the cells appear from the right first, and each consecutive cell is placed to the left of that one.

The frame Attribute (Deprecated)

The frame attribute is supposed to control the appearance of the outermost border of the whole table, referred to here as its frame, with greater control than the border attribute. If both the frame and border attributes are used, the frame attribute takes precedence. The syntax is:

frame=”frameType”

The following table shows the possible values for the frame attribute.

Value

Purpose

void

No outer border (the default)

above

A border on the top only

below

A border on the bottom only

hsides

A border on the top and bottom

lhs

A border on the left side of table

rhs

A border on the right side of table

vsides

A border on the left and right sides of table

box

A border on all sides

border

A border on all sides

Support for the frame attribute is not perfect across browsers, and its role has been replaced by the CSS border property, which can give better results.

The rules Attribute (Deprecated)

The rules attribute is used to indicate which inner borders of the table should be displayed. For example, you can just specify that the rows or columns should have lines between each of them. Here is the syntax; the default value is none.

rules=”ruleType”

The following table shows the possible values for the rules attribute:

Value

Purpose

none

No inner borders (the default)

groups

Displays inner borders between all table groups (groups are created by the <thead>, <tbody>, <tfoot>, and <colgroup> elements)

rows

Displays horizontal borders between each row

cols

Displays vertical borders between each column

all

Displays horizontal and vertical borders between each row and colum

Again, support for this attribute is not perfect, and it has been deprecated in favor of the CSS border property, which achieves better results.

The summary Attribute

The summary attribute is supposed to provide a summary of the table’s purpose and structure for non-visual browsers such as speech browsers or Braille browsers. The value of this attribute is not rendered in IE or Firefox, but if the text before the table doesn’t clearly explain what will be found in the table, you should aim to use it in your pages:

summary=”Table shows the operating profit for the last four quarters. The first column indicates the quarter, the second indicates outgoings, the third indicates receipts, and the fourth indicates profit.”

The width Attribute (Deprecated)

The width attribute is used to specify the width of the table, and usually its value is given in pixels.

width=”500”

It is also possible to use a percentage of the available space, the available space generally being the width of the browser, unless the table sits inside another element within the body of the page, in which case it is a percentage of the size of the containing element.

width=”90%”

The <tr> Element Contains Table Rows

The <tr > element is used to contain each row in a table. Anything appearing within a <tr> element should appear on the same row. It can carry five attributes, three of which have been deprecated in favor of using CSS.

align bgcolor char charoff valign

The align Attribute (Deprecated)

The align attribute specifies the position of the content of all of the cells in the row.

align=”alignment”

The table that follows lists the possible values for the align attribute:

Value

Purpose

left

Content is left-aligned.

right

Content is right-aligned.

center

Content is centered horizontally within the cell.

justify

Text within the cell is justified to fill the cell.

char

Cell contents are aligned horizontally around the first instance of a specific character (for example, numbers could be aligned around the first instance of a decimal point).

By default, any <td> cells are usually left-aligned, whereas any <th> cells are usually centered. While Firefox 2+ supports justified text, IE does not, and neither IE nor Firefox support the value char.

The bgcolor Attribute (Deprecated)

The bgcolor attribute sets the background color for the row. The value of this attribute should be either a color name or a hex code or color value.

bgcolor=”red”

The bgcolor attribute is commonly used on the <tr> element to shade alternate rows of a table with different colors, thus making it easier to read across each row.

The char Attribute

If the align attribute has been given a value of char, then the char attribute is used to specify that the contents of each cell within the row will be aligned around the first instance of a particular character known as an axis character. The default character for this attribute is the decimal place, and the idea is that decimal figures would be aligned by the decimal point like so:

13412.22

232.147

2449.6331

2.12

The syntax is as follows:

char=”.”

Unfortunately, this potentially very helpful attribute is not supported at the time of this writing, and there is no requirement for browsers to support it.

The charoff Attribute

The charoff attribute is used in association with the char attribute, and indicates an offset for the char attribute. For example, if it is given a value of 2, then the elements are aligned with the character that is two characters along from the one specified by the char attribute. It can also take a negative value. If this attribute is omitted, the default behavior is to make the offset the equivalent of the longest amount of text content that appeared before the character specified in the char attribute.

charoff=”2”

Unfortunately, this attribute is not supported at the time of this writing, and there is no requirement for browsers to support it.

The valign Attribute (Deprecated)

The valign attribute specifies the vertical alignment of the contents of each cell in the row. The syntax is as follows:

valign=”verticalPosition”

The table that follows shows the possible values of the valign attribute:

Value

Purpose

top

Aligns content with the top of the cell

middle

(Vertically) aligns content in the center of a cell

bottom

Aligns content with the bottom of the cell

baseline

Aligns content so that the first line of text in each cell starts on the same horizontal line

The <td> and <th> Elements Represent Table Cells

Every cell in a table will be represented by either a <td> element for cells containing table data or a <th> element for cells containing table headings.By default, the contents of a <th> element are usually displayed in a bold font, horizontally aligned in the center of the cell. The content of a <td> element, meanwhile, will usually be displayed left-aligned and not in bold (unless otherwise indicated by CSS or another element).

The <td > and <th> elements can both carry the same set of attributes, and the attribute only applies to that one cell carrying it. Any effect these attributes have will override settings for the table as a whole or any containing element (such as a row).In addition to the universal attributes and the basic event attributes, the <td> and <th> elements can also carry the following attributes:

abbr align axis bgcolor char charoff colspan headers

height nowrap rowspan scope valign width

The abbr Attribute

The abbr attribute is used to provide an abbreviated version of the cell’s content.

abbr=”description of services”

While the major browsers do not currently support this attribute, it’s possible that it will be used by some of the increasing number of devices with small screens accessing the Internet. For example, if a browser with a small screen is being used to view the page, the content of this attribute could be displayed instead of the full content of the cell.

The align Attribute (Deprecated)

The align attribute sets the horizontal alignment for the content of the cell.

align=”alignment”

The possible values for the align attribute are left, right, center, justify, and char, each of which was described earlier in “The < tr > Element Contains Table Rows” section.

The axis Attribute

The axis attribute allows you to add conceptual categories to cells and therefore represent n-dimensional data. The value of this attribute would be a comma-separated list of names for each category the cell belonged to.

axis=”heavy, old, valuable”

Rather than having a visual formatting effect, this attribute allows you to preserve data, which then may be used programmatically, such as querying for all cells belonging to a certain category.

The bgcolor Attribute (Deprecated)

The bgcolor attribute sets the background color for the cell. The value of this attribute should be either a color name or a hex code.

bgcolor=”red”

It has been replaced by the background-color property in CSS.

The char Attribute

The char attribute specifies a character, the first instance of which should be used to horizontally align the contents of a cell. (See the full description in the “The char Attribute” subsection within the “The <tr> Element Contains Table Rows” section earlier in the chapter.)

The charoff Attribute

The charoff attribute specifies the number of offset characters that can be displayed before the character specified as the value of the char attribute. (See the full description in the “The charoff Attribute” subsection within the “The <tr> Element Contains Table Rows ” section earlier in the chapter.)

The colspan Attribute

The colspan attribute is used when a cell should span across more than one column. The value of the attribute specifies how many columns of the table a cell will span across. (See the section “Spanning Columns Using the colspan Attribute” later in this chapter.)

colspan=”2”

The headers Attribute

The headers attribute is used to indicate which headers correspond to that cell. The value of the attribute is a space-separated list of the header cells’ id attribute values:

headers=”income q1”

The main purpose of this attribute is to support voice browsers. When a table is being read to you, it can be hard to keep track of which row and column you are on; therefore, the header attribute is used to remind users which row and column the current cell’s data belongs to.

The height Attribute (Deprecated)

The height attribute allows you to specify the height of a cell in pixels, or as a percentage of the available space:

height=”20” or height=”10%”

It has been replaced by the CSS height property.

The nowrap Attribute (Deprecated)

The nowrap attribute is used to stop text from wrapping onto a new line within a cell. You would use nowrap only when the text really would not make sense if it were allowed to wrap onto the next line (for example, a line of code that would not work if it were spread across two lines). When it was initially introduced in HTML, it was used without an attribute value, but that would not be allowed in XHTML. Rather, you would have to use the following:

nowrap=”nowrap”

The rowspan Attribute

The rowspan attribute specifies the number of rows of the table a cell will span across, the value of the attribute being the number of rows the cell stretches across. (See the example in the section “Spanning Rows Using the rowspan Attribute” later in this chapter.)

rowspan=”2”

The scope Attribute

The scope attribute can be used to indicate which cells the current header provides a label or header information for. It can be used instead of the headers attribute in basic tables, but does not have much support.

scope=”range”

The table that follows shows the possible values of the attribute:

Value

Purpose

row

Cell contains header information for that row.

col

Cell contains header information for that column.

rowgroup

Cell contains header information for that rowgroup (a group of cells in a row created using the <thead>, <tbody>, or <tfoot> elements).

colgroup

Cell contains header information for that colgroup (a group of columns created using the <col> or <colgroup> element, both of which are discussed later in the chapter).

The valign Attribute (Deprecated)

The valign attribute allows you to specify the vertical alignment for the content of the cell. Possible values are top, middle, bottom, and baseline, each of which was discussed earlier in the chapter in the subsection entitled “The valign Attribute” within the section “The <tr> Element Contains Table Rows.”

The width Attribute (Deprecated)

The width attribute allows you to specify the width of a cell in pixels, or as a percentage of the table:

width=”150” or width=”30%”

You only need to specify the width attribute for the cells in the first row of a table, and the rest of the rows will follow the first row’s cell widths. If you had already specified a width attribute for the <table> element, and the widths of individual cells add up to more than that width, most browsers will squash those cells to fit them into the width of the table.

You can also add a special value of *, which means that this cell will take up the remaining space available in the table. So if you have a table that is 300 pixels wide and the first two cells in a row are specified as being 50 pixels wide, if the third cell has a value of *, it will take up 200 pixels — the remaining width of the table. If the width of the table had not been specified, then the third column would take up the remaining width of the browser window. It is worth noting that you cannot specify different widths for different <td> elements that belong in the same column. So, if the first row of a table had three <td> elements whose widths were 100 pixels, the second row could not have one <td> element whose width was 200 pixels and two that were 50 pixels.

In this example, you will create a table that shows the opening hours of the Example Café web site we have been working on. The table will look like the one shown in Figure 4-9.

Figure 4-9

1. Start off by opening the contact.html file in your text or XHTML editor; we will be adding a table to show serving hours beneath the e-mail link.

 2. The table is contained within the <table> element and its content is then written out a row at a time. The table has three rows and eight columns.

Starting with the top row, you have eight table heading elements. The first <th> element is empty because the top-left corner cell of the table is empty. The next seven elements contain the days of the week.In the second row of the table, the first cell acts as a heading for that row, indicating the meal (breakfast). The remaining cells show what times these meals are served. The third row follows the same format as the second row but shows times for lunch.

<table>

<tr>

<th></th>

<th>Monday</th>

<th>Tuesday</th>

<th>Wednesday</th>

<th>Thursday</th>

<th>Friday</th>

<th>Saturday</th>

<th>Sunday</th>

</tr>

<tr>

<th>Breakfast</th>

<td>7:00am – 10:00am</td>

<td>7:00am – 10:00am</td>

<td>7:00am – 10:00am</td>

<td>7:00am – 10:00am</td>

<td>7:00am – 11:00am</td>

<td>8:00am – 11:30pm</td>

<td>8:00am – 11:30pm</td>

</tr>

<tr>

<th>Lunch</th>

<td>11:30am – 2:30pm</td>

<td>11:30am – 2:30pm</td>

<td>11:30am – 2:30pm</td>

<td>11:30am – 2:30pm</td>

<td>11:30am – 2:30pm</td>

<td>11:30am – 3:30pm</td>

<td>11:30am – 3:30pm</td>

</tr>

</table>

</body>

As long as you accept that each row is written out in turn, you will have no problem creating quite complex tables.

3. Save your file as contact.html.

Adding a <caption> to a Table

Whether your table shows results for a scientific experiment, values of stocks in a particular market, or what is on television tonight, each table should have a caption so that visitors to your site know what the table is for. Even if the surrounding text describes the content of the table, it is good practice to give the table a formal caption using the <caption> element. By default, most browsers will display the contents of this element centered above the table, as shown in Figure 4-10 in the next section. The <caption> element appears directly after the opening <table> tag; it should come before the first row:

<table>

<caption> Opening hours for the Example Cafe</caption>

<tr>

By using a <caption> element, rather than just describing the purpose of the table in a previous or subsequent paragraph, you are directly associating the content of the table with this description — and this association can be used by screen readers and by applications that process web pages (such as search engines).

Grouping Sections of a Table

In this section, you are going to look at some techniques that allow you to group together cells, rows, and columns of a table, and learn the advantages that doing this can bring. In particular, you will see how to do the following:

Use the rowspan and colspan attributes to make cells stretch over more than one row or column

Split a table into three sections: a head, body, and foot Group columns using the <colgroup> element

      Share attributes between unrelated columns using the <col> element

Spanning Columns Using the colspan Attribute

As you saw when looking at the <td > and <th> elements, both can carry an attribute called colspan that allows the table cell to span (or stretch) across more than one column.

If you look at Figure 4-10, you can see a table that has three rows; the cells of the table are shaded to illustrate the colspan attribute in action:

      The first row has three columns of equal width, and there is one cell for each column.

In the second row, the first cell is the width of one column, but the second cell spans the width of two columns.

      The third row has just one cell that spans all three columns.

Figure 4-10

Let’s take a look at the code for this example to see how the colspan attribute is used. This example also uses the deprecated border, width, height, and bgcolor attributes in order to illustrate a point visually :

<table border=”1”>

<caption>Spanning columns using the colspan attribute</caption> <tr>

<td bgcolor=”#efefef” width=”100” height=”100”>&nbsp;</td> <td bgcolor=”#999999” width=”100” height=”100”>&nbsp;</td> <td bgcolor=”#000000” width=”100” height=”100”>&nbsp;</td>

</tr>

<tr>

<td bgcolor=”#efefef” width=”100” height=”100”>&nbsp;</td> <td colspan=”2” bgcolor=”#999999”>&nbsp;</td>

</tr>

<tr>

<td colspan=”3” bgcolor=”#efefef” height=”100”>&nbsp;</td> </tr>

</table>

In the first row, you can see that there are three <td> elements, one for each cell. In the second row, there are only two <td> elements, and the second of these elements carries a colspan attribute. The value of the colspan attribute indicates how many columns the cell should stretch across. In this case, the second cell spans two columns; therefore, it has a value of 2. In the final row, there is just one <td> element, and this time the colspan attribute has a value of 3, which indicates that it should take up three columns.

As we mentioned at the start of this chapter, when dealing with tables you have to think in terms of grids. This grid is three cells wide and three rows tall, so the middle row could not have two equal-sized cells (because they would not fit in the grid — you cannot have a cell spanning 1.5 columns). An example of where the colspan attribute might be useful is in creating a timetable or schedule where the day is divided into hours — some slots lasting one hour, others lasting two to three hours. You might also have noticed the use of the non-breaking space character (&nbsp;) in the cells, which is included so that the cell has some content; without content for a table cell, some browsers will not display the background color (whether that color is specified using CSS or the deprecated bgcolor attribute).

Spanning Rows Using the rowspan Attribute

The rowspan attribute does much the same thing as the colspan attribute, but it works in the opposite direction: it allows cells to stretch vertically across cells. You can see the effect of the rowspan attribute in Figure 4-11.

 

Figure 4-11

When you use a rowspan attribute, the corresponding cell in the row beneath it must be left out :

<table border=”1”>

<caption>Spanning rows using the colspan attribute</caption> <tr>

<td bgcolor=”#efefef” width=”100” height=”100”>&nbsp;</td> <td bgcolor=”#999999” width=”100” height=”100”>&nbsp;</td>

<td rowspan=”3” bgcolor=”#000000” width=”100” height=”100”>&nbsp;</td>

</tr>

<tr>

<td bgcolor=”#efefef” height=”100”>&nbsp;</td> <td rowspan=”2” bgcolor=”#999999”>&nbsp;</td>

</tr>

<tr>

<td bgcolor=”#efefef” height=”100”>&nbsp;</td> </tr>

</table>

The rowspan and colspan attributes were popular with designers who used tables to control the layout pages, but tables are rarely used to lay out pages these days, and this technique has largely been replaced by the use of CSS to control layouts.

Splitting Up Tables Using a Head, Body, and Foot

There are occasions when you may wish to distinguish between the body of a table (where most of the data is held) and the headings or maybe even the footers. For example, think of a bank statement: you may have a table where the header contains column headings, the body contains a list of transactions, and the footer contains the balance in the account. If the table is too long to show on a screen, then the header and footer might remain in view all the time, while the body of the table gains a scrollbar. Similarly, when printing a long table that spreads over more than one page, you might want the browser to print the head and foot of a table on each page. Unfortunately, the main browsers do not yet support these ideas. However, if you add these elements to your tables, you can use CSS to attach different styles to the contents of the <thead>, <tbody>, and <tfoot> elements. It can also help those who use aural browsers, which read pages to users.

The three elements for separating the head, body, and foot of a table are:

      <thead> to create a separate table header

<tbody> to indicate the main body of the table <tfoot> to create a separate table footer

A table may also contain several <tbody> elements to indicate different “pages,” or groups of data.

Note that the <tfoot> element must appear before the <tbody> element in the source document.

Here you can see an example of a table that makes use of these elements :

<table>

<thead>

<tr>

<th>Transaction date</th>

<th>Payment type and details</th>

<th>Paid out</th>

<th>Paid in</th>

<th>Balance</th>

</tr>

</thead>

<tfoot>

<tr>

<td></td>

<td></td>

<td>$1970.27</td>

<td>$2450.00</td>

<td>$8940.88</td>

</tr>

</tfoot>

<tbody>

<tr>

<td>12 Jun 09</td>

<td>Amazon.com</td >

<td>$49.99</td>

<td></td>

<td>$8411.16</td>

</tr>

<tr>

<td>13 Jun 09</td>

<td>Total</td>

<td>$60.00</td>

<td></td>

<td>$8351.16</td>

</tr>

<tr>

<td>14 Jun 09</td>

<td>Whole Foods</td>

<td>$75.28< /td>

<td></td>

<td>$8275.88</td>

</tr>

<tr>

<td>14 Jun 09</td>

<td>Visa Payment</td>

<td>$350.00</td>

<td></td>

<td>$7925.88</td>

</tr>

<tr>

<td>15 Jun 09</td>

<td>Cheque 122501</td>

<td></td>

<td>$1450.00< /td>

<td>$9375.88</td>

</tr>

</tbody>

<tbody>

<tr>

<td>17 Jun 09</td>

<td>Murco</td>

<td>$60.00</td>

<td></td>

<td>$9315.88</td>

</tr>

<tr>

<td>18 Jun 09</td>

<td>Wrox Press</td>

<td></td>

<td>$1000.00</td>

<td>$10315.88</td>

</tr>

<tr>

<td>18 Jun 09</td >

<td>McLellans Bakery </td>

<td>$25.00</td>

<td></td>

<td>$10290.88</td>

</tr>

<tr>

<td>18 Jun 09</td>

<td>Apple Store</td>

<td>$1350.00</td>

<td></td>

<td>$8940.88</td>

</tr>

</tbody>

</table>

Figure 4-12 shows what this example looks like in Firefox, which supports the thead, tbody, and tfoot elements. Note that this example uses CSS to give the header and footer of the table a background shade.

Figure 4-12

All three elements carry the same attributes. In addition to the universal attributes, they can carry the following attributes (each of which was covered in the earlier section “Basic Table Elements and Attributes”):

align char charoff valign

Grouping Columns Using the <colgroup> Element

If two or more columns are related, you can use the <colgroup> element to explain that those columns are grouped together. For example, in the following table, there would be six columns. The first four columns are in the first column group, and the next two columns are in the second column group :

<table>

<colgroup span=”4” class=”mainColumns” />

<colgroup span=”2” class=”subTotalColumns” />

<tr>

<td>1</td>

<td>2</td>

<td>3</td>

<td>4</td>

<td>5</td>

<td>6</td>

</tr>

</table>

When the <colgroup> element is used, it comes directly after the opening <table> tag and carries a span attribute, which is used to indicate how many columns the group contains.In this example, the class attribute is used to attach CSS rules that tell the browser the width of each column in the group and the background color for each cell. But it is worth noting that some browsers support only a subset of the CSS rules for this element.

You can see what this example looks like in Figure 4-13.

Figure 4-13

In addition to the universal attributes, the <colgroup> element can carry the following attributes:

align char charoff span valign width

Columns Sharing Styles Using the <col> Element

The <col> element was introduced to specify attributes of the columns in a <colgroup> (such as width or alignment of cells within that column). Unlike the <colgroup> element, the <col> element does not imply structural grouping and is therefore more commonly used for presentational purposes. The <col> elements are always empty elements, which means they do not have any content, although they do carry attributes. For example, the following table would have six columns, and the first five, while not a group in their own right, could be formatted differently than the last column because it belongs to a separate set :

<table>

<colgroup span=”6”>

<col span=”5” class=”mainColumns” />

<col span=”1” class=”totalColumn” />

</colgroup>

<tr>

<td></td>

<td></td>

</tr>

</table>

You can see what this looks like in Figure 4-14.

Figure 4-14

The attributes that the <col> element can carry are the same as for the <colgroup> element.

Nested Tables

As mentioned earlier in the chapter, you can include markup inside a table cell, as long as the whole element is contained within that cell. This means you can even place another entire table inside a table cell, creating what’s called a nested table. Figure 4-15 shows you an example of a table that shows a schedule for a weekend of activities.

Figure 4-15

In the bottom-right cell of this table is a second table that divides up the attendees into two groups.

<table>

<tr>

<th></th>

<th>Morning</th>

<th>Afternoon</th>

</tr>

<tr>

<th>Saturday</th>

<td>Cycling</td>

<td>Fishing</td>

</tr>

<tr>

<th>Sunday</th>

<td>Rowing</td>

<td>

<table>

<tr>

< th>Group 1</th>

<th>Group 2</th>

</tr>

<tr>

<td>Water ski-ing</td>

<td>Wake boarding</td>

</tr>

</table>

</td>

</tr>

</table>

Now that you’ve seen how to create a nested table, it is worth noting that they should be used very sparingly, because they are quite hard for those who rely upon screen readers to follow. You are about to see this in the next section.

Accessible Tables

By their nature, tables can contain a lot of data and they provide a very helpful visual representation of this information. When looking at a table, it is easy to scan across rows and up and down columns to find a particular value or compare a range of values. If you think back to the examples you saw at the very start of the chapter (the NFL sports results or the train timetable), you would not need to read all the content of the table just to find out how your team is doing this season or when a train is leaving. However, for those who listen to pages on a voice browser or a screen reader, tables can be much harder to understand. For example, if you imagine having a table read to you, it would be much more difficult to compare entries across a row or column because you have to remember what you have heard so far (it is not as easy to scan back and forth).

Yet with a little thought or planning, you can make tables a lot easier for all to understand. Here are some things you can do to ensure your tables are easy to understand:

Add captions to your tables. The <caption> element clearly associates a caption with a table, and the screen reader will read the caption to the user before they see the table so that they know what to expect. If the listener knows what to expect, it will be easier to understand the information.

Always try to use the <th> element to indicate a table heading. Always put headings in the first row and the first column.

Avoid using nested tables (like the one you saw in the previous section), as this will make it harder for the user of a screen reader to follow.

Avoid using rowspan and colspan attributes, which again make it harder for the user with a screen reader to follow. If you do use them, make sure that you use the scope and headers attributes, which are discussed shortly.

Learn how a voice browser or screen reader would read a table, and the order in which the cells are read out; this will help you to understand how to structure your tables for maximum ease of use (we will see examples of this in the following section).

If you use the scope and headers attributes to clearly indicate which headings apply to which rows and columns, then screen readers can help users retrieve headings for a particular cell. If you imagine someone having a table read to him or her, the screen reader will often give the user an option to hear the headers that are relevant to that cell again (without having to go up to the first row or back to the first cell in the column to hear the heading that corresponds with that cell).

You already saw how to add a caption to a table, so let’s move on and see how tables are read to a user, or how they are linearized.

How to Linearize Tables

When a screen reader is being used to read a table, it will tend to perform what is known as linearization, which means that the reader starts at the first row and reads the cells in that row from left to right, one by one, before moving on to the next row, and so on until the reader has read each row in the table. Consider the following simple table :

<table border=”1”>

<tr>

<td>Column 1, Row 1</td>

<td>Column 2 Row 1</td>

</tr>

<tr>

<td>Column 1, Row 2</td>

<td>Column 2, Row 2</td>

</tr>

</table>

Figure 4-16 shows what this simple table would look like in a browser.

Figure 4-16

The order in which the cells in Figure 4-16 would be read is therefore:

Column 1 Row 1

Column 2 Row 1

Column 1 Row 2

Column 2 Row 2

This small example is fairly easy to follow. But imagine a larger table: the headings will be read first, followed by a row of data. If the table had several more columns, it would be very hard to remember which column you were in. (Even worse, if you use nested tables, it becomes far harder for users to follow where they are, because one table cell can contain an entirely new table that often has different numbers of rows or columns.) Luckily, most screen readers are able to remind the user of the column and row they are currently in, but this works far better when the table uses <th> elements for headers. And if you are building a complex table, you can also enhance this information using the id, scope, and headers attributes, covered in the following section.

Using the id, scope, and headers Attributes

The id, scope, and headers attributes have already been mentioned in this chapter, when we looked at the attributes that the <td> and <th> elements can carry. Here we will take a look at how they can be used to record the structure of a table better and make it more accessible.

When you make a cell a heading, adding the scope attribute to the <th> element, helps you indicate which cells that element is the heading for. If you give it a value of row, you are indicating that this

element is the header for that row; given the value of column, it indicates that it is the header for that column. You can also have values for a rowgroup or columngroup.

Value

Purpose

row

Cell contains header information for that row.

col

Cell contains header information for that column.

rowgroup

Cell contains header information for that rowgroup — a group of cells in a row created using the <thead>, <tbody>, or <tfoot> elements. (There is no corresponding element for columns like the <colgroup> element.)

colgroup

Cell contains header information for that colgroup (a group of columns created using the <col> or <colgroup> element, both of which are discussed later in the chapter)

The headers attribute performs the opposite role to the scope attribute, because it is used on <td > elements to indicate which headers correspond to that cell. The value of the attribute is a space-separated list of the header cells’ id attribute values, so here you can tell that the headers for this cell would have id attributes whose values are income and q1.

headers=”income q1”

The main purpose of this attribute is to support voice browsers. When a table is being read to you, it can be hard to keep track of which row and column you are on; therefore, the header attribute is used to remind users which row and column the current cell’s data belongs to.

In this Examplet, you are going to create a new page for the Example Café web site featuring a timetable for a weekend cookery course, with morning and afternoon sessions over two days. It should look like the screenshot in Figure 4-17.

Figure 4-17

While you cannot see it from this screenshot, the table is specifically designed to be accessible for those with visual impairments.

1. Because this example contains deprecated attributes, you need to set up the skeleton of this page to handle a Transitional XHTML 1.0 document:

<?xml version=”1.0” encoding=”UTF-8”?>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en”> <head>

<title>Ultimate brunch course</title>

</head>

<body>

</body>

</html>

2. The table has three rows and three columns; the first row and the left column contain headings and therefore use <th> elements. The remaining table cells use a <td> element. While you are adding these elements, you’ll add in some content for the table, too:

<body>

<table>

<tr>

<th></th>

<th>Tuesday</th>

<th>Wednesday</th>

</tr>

<tr>

<th>Morning</th>

<td>Baking bread: loaves, croissants and muffins.</td>

<td>Sweet treats: pancakes and waffles.</td>

</tr>

<tr>

<th>Afternoon</th>

<td>Eggs 4 ways: boiled, scrambled, poached, fried.</td>

<td>Fry pan specials: Fritters and hash browns.</td> </tr >

</table>

</body>

3. The next stage is to add id attributes to the <th> elements that have content, and header attributes to the <td> elements to indicate which headers apply to those elements; this approach improves accessibility for visitors who use screen readers. The value of the header attributes should correspond to the values of the id attributes indicating which headings correspond to each cell:

<table>

<tr>

<th></th>

<th id=”Saturday”>Saturday</th>

<th id=”Sunday”>Sunday</th>

</tr>

<tr>

<th id=”Morning”>Morning</th>

<td headers=”Saturday Morning” abbr=”Bread”>Baking bread: loaves, croissants and muffins.</td>

<td headers=”Sunday Morning” abbr=”Eggs”>Eggs 4 ways: boiled, scrambled, poached, fried </td>

</tr>

<tr>

<th id=”Afternoon”>Afternoon</th>

<td headers=”Saturday Afternoon” abbr=”Sweet breakfasts”>Sweet treats:

pancakes and waffles.</td>

<td headers=”Sunday Afternoon” abbr=”Fried foods”>Fry pan specials:

Fritters and hash browns.</td>

</tr>

</table>

4. Save your file as course.html. To be honest, this example is quite a bit more complex than most tables you will come across. Not many people have gotten into the practice of using the id and header attributes on <table> elements, but it makes tables a lot easier to use for those with visual impairments, in particular on larger tables that have a lot of columns and rows. Neither will you often see the abbr attribute used on table cells. In fact, if you look at the code for other people’s web sites, you are still more likely to come across the use of lots of deprecated attributes rather than these attributes.

Including attributes like these will help set you apart from other coders who have not yet learned to make their tables more accessible. Furthermore, awareness of accessibility issues is required in an increasing number of jobs, so you should learn how to use such attributes.

Summary

In this chapter, you have seen how tables can be a powerful tool when creating pages. You have seen how all tables are based on a grid pattern and use the four basic elements: <table>, which contains each table; <tr>, which contains the rows of a table; <td >, which contains a cell of table data; and <th>, which represents a cell that contains a heading. You have also seen how you can add headers, footers, and captions to tables. It is particularly helpful to add a <thead> and <tfoot> element to any table that may be longer than a browser window or sheet of printed paper, as these could help a reader relate between the content and the information in headers or footers.

You can now make cells span both columns and rows, although you should avoid doing this in tables that contain data, as it makes them harder for aural browsers to read to a user. You have also seen how to group columns so that you can preserve structure, and so they can share styles and attributes. Finally, you saw some of the accessibility issues regarding use of tables. It is important to be aware of the process of linearization, which a screen reader performs before reading a table to a user, so that your

This Is A Custom Widget

This Sliding Bar can be switched on or off in theme options, and can take any widget you throw at it or even fill it with your custom HTML Code. Its perfect for grabbing the attention of your viewers. Choose between 1, 2, 3 or 4 columns, set the background color, widget divider color, activate transparency, a top border or fully disable it on desktop and mobile.

This Is A Custom Widget

This Sliding Bar can be switched on or off in theme options, and can take any widget you throw at it or even fill it with your custom HTML Code. Its perfect for grabbing the attention of your viewers. Choose between 1, 2, 3 or 4 columns, set the background color, widget divider color, activate transparency, a top border or fully disable it on desktop and mobile.