Chapter 6. Using Tables to Display Information


WHAT YOU’LL LEARN IN THIS CHAPTER:

• How to create simple tables

• How to control the size of tables

• How to align content and span rows and columns within tables


In this chapter, you learn how to build HTML tables you can use to control the spacing, layout, and appearance of tabular data in your web content. Although you can achieve similar results using CSS, there are definitely times when a table is the best way to present information, and you’ll find that tables are useful for arranging information into rows and columns. I will also explain how designers have used tables for page layout in the past and how that isn’t always the best idea. Before we begin, just remember a table is simply an orderly arrangement of content into vertical columns and horizontal rows.

Creating a Simple Table

A table consists of rows of information with individual cells inside. To make tables, you have to start with a <table> tag. Of course, you end your tables with the </table> tag. If you want the table to have a border, use a border attribute to specify the width of the border in pixels. A border size of 0 or none (or leaving the border attribute out entirely) will make the border invisible, which is handy if you find yourself using a table as a page layout tool (not recommended).


Tip

As you read this chapter, think about how arranging text into tables could benefit your web content. The following are some specific ideas to keep in mind:

• The most obvious application of tables is to organize tabular information, such as a multicolumn list of names and numbers.

• Whenever you need multiple columns of text or images, tables are the answer.


With the <table> tag in place, the next thing you need is the <tr> tag. The <tr> tag creates a table row, which contains one or more cells of information before the closing </tr>. To create these individual cells, use the <td> tag (<td> stands for table data). Place the table information between the <td> and </td> tags. A cell is a rectangular region that can contain any text, images, and HTML tags. Each row in a table consists of at least one cell. Multiple cells within a row form columns in a table.

There is one more basic tag involved in building tables. The <th> tag works exactly like a <td> tag except <th> indicates that the cell is part of the heading of the table. Most web browsers render the text in <th> cells as centered and boldface.


Tip

Some style properties enable you to take much more control over table borders. For example, you can set the border width (border-width), style (border-style), and color (border-color). These properties work fine, but you have to apply them to each table element, which can be cumbersome even if you use classes for your table row or table cell elements.


You can create as many cells as you want, but each row in a table should have the same number of columns as the other rows. The HTML code shown in Listing 6.1 creates a simple table using only the four table tags I’ve mentioned thus far. Figure 6.1 shows the resulting page as viewed in a web browser.

Figure 6.1 The HTML code in Listing 6.1 creates a table with six rows and four columns.

image

Listing 6.1 Creating Tables with the <table>, <tr>, <td>, and <th> Tags


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
    <title>Baseball Standings</title>
  </head>

  <body>
  <h1>Baseball Standings</h1>
    <table>
      <tr>
        <th>Team</th>
        <th>W</th>
    <th>L</th>
        <th>GB</th>
      </tr>
      <tr>
        <td>Los Angeles Dodgers</td>
        <td>62</td>
        <td>38</td>
        <td>—</td>
      </tr>
      <tr>
        <td>San Francisco Giants</td>
        <td>54</td>
        <td>46</td>
        <td>8.0</td>
      </tr>
      <tr>
        <td>Colorado Rockies</td>
        <td>54</td>
        <td>46</td>
        <td>8.0</td>
      </tr>
      <tr>
         <td>Arizona Diamondbacks</td>
         <td>43</td>
         <td>58</td>
         <td>19.5</td>
      </tr>
      <tr>
         <td>San Diego Padres</td>
         <td>39</td>
         <td>62</td>
         <td>23.5</td>
      </tr>
    </table>
  </body>
</html>



Tip

HTML ignores extra spaces between words and tags. However, you might find your HTML tables easier to read (and less prone to time-wasting errors) if you use spaces to indent <tr> and <td> tags, as I did in Listing 6.1.


The table in the example contains baseball standings, which are perfect for arranging in rows and columns—if not a little plain. You’ll learn to jazz things up a bit during this chapter. The headings in the table show the Team, Wins (W), Losses (L), and Games Behind (GB) in the standings.

Although we did not apply any styles to the HTML in Listing 6.1, you can use any text style in a table cell. However, styles or HTML tags used in one cell don’t carry over to other cells, and tags from outside the table don’t apply within the table. For example, consider the following table:

<p style="font-weight:bold">
  <table>
    <tr>
      <td style="font-style:italic">hello</td>
      <td>there</td>
    </tr>
  </table>
</p>

In this example, the <p> tag is used around a table to demonstrate how tables are immune to outside tags. The word there would be neither boldface nor italic because neither the font-weight:bold style outside the table nor the font-style:italic style from the previous cell affects it. In this example, the word hello is in italics, however.

To boldface the words hello and there, change the table code to this:

<table style="font-weight:bold">
  <tr>
    <td style="font-style:italic">hello</td>
    <td>there</td>
  </tr>
</table

In this example, both words are in bold and the word hello is italicized as well. Of course, you don’t have to apply styles at the table level. The font-weight:bold style could just as easily be applied to each cell individually; you could repeat style="font-weight:bold" in each cell or create a class in your style sheet and use class="classname" in each cell—it’s your choice.

Controlling Table Sizes

When a table width is not specified, the size of a table and its individual cells automatically expand to fit the data you place into it. However, you can choose to control the exact size of the entire table by using width and/or height styles in the <table> tag. You can also control the size of each cell by putting width and height styles in the individual <td> tags. The width and height styles can be specified as either pixels or percentages. For example, the following code creates a table 500 pixels wide and 400 pixels high:

<table style="width:500px; height:400px">


Note

There are actually width and height HTML attributes that were deprecated in the move to XHTML, and you might still see them when you look at another designer’s code. These attributes still work in web browsers, but you should use the width and height style properties instead because they represent the appropriate use of XHTML.


To make the first cell of the table 20% of the total table width and the second cell 80% of the table width, type the following:

<table style="width:100%">
  <tr>
    <td style="width:20%">skinny cell</td>
    <td style="width:80%">fat cell</td>
  </tr>
</table>

Notice that the table is sized to 100%, which ensures the table fills the entire width of the browser window. When you use percentages instead of fixed pixel sizes, the table will resize automatically to fit any size browser window while maintaining the aesthetic balance you’re after. In this case, the two cells within the table are automatically resized to 20% and 80% of the total table width, respectively.

In Listing 6.2, the simple table from Listing 6.1 is expanded to show specific control over table cell widths.

Listing 6.2 Specifying Table Cell Widths


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
    <title>Baseball Standings</title>
  </head>

  <body>
  <h1>Baseball Standings</h1>
    <table>
      <tr>
        <th style="width:35px;"></th>
        <th style="width:175px;">Team</th>
        <th style="width:25px;">W</th>
        <th style="width:25px;">L</th>
        <th style="width:25px;">GB</th>
      </tr>
      <tr>
        <td><img src="losangeles.gif" alt="Los Angeles
          Dodgers" /></td>
        <td>Los Angeles Dodgers</td>
        <td>62</td>
        <td>38</td>
        <td>—</td>
      </tr>
      <tr>
        <td><img src="sanfrancisco.gif" alt="San Francisco
           Giants" /></td>
        <td>San Francisco Giants</td>
        <td>54</td>
        <td>46</td>
        <td>8.0</td>
      </tr>
      <tr>
        <td><img src="colorado.gif" alt="Colorado
           Rockies" /></td>
        <td>Colorado Rockies</td>
        <td>54</td>
        <td>46</td>
        <td>8.0</td>
      </tr>
      <tr>
        <td><img src="arizona.gif" alt="Arizona
           Diamondbacks" /></td>
        <td>Arizona Diamondbacks</td>
        <td>43</td>
        <td>58</td>
        <td>19.5</td>
      </tr>
      <tr>
        <td><img src="sandiego.gif" alt="San Diego Padres" /></td>
        <td>San Diego Padres</td>
        <td>39</td>
        <td>62</td>
        <td>23.5</td>
      </tr>
    </table>
  </body>
</html>


You can see the consistent column widths in Figure 6.2.

Figure 6.2 The HTML code in Listing 6.2 creates a table with six rows and five columns, with specific widths used for each column.

image

There are two differences between the code from Listing 6.1 and the code used in Listing 6.2. First, an additional column has been added in Listing 6.2; this column does not have a heading, but the <th></th> tag pair is still present in the first table row. In rows two through six, this additional column contains an image (the <img /> tag). The second difference in Listing 6.2 is the addition of a specific width style for each <th> element in the first row. The first column is defined as 35px wide, the second 175px wide, and the third, fourth, and fifth columns are each 25px wide.

Also note that these widths are not repeated in the <td> elements in subsequent rows. Technically you must define only the widths in the first row; the remaining rows will follow suit because they are all part of the same table. However, if you used another formatting style (such as a style to change font size or color), that style must be repeated for each element that should have those display properties.

Alignment and Spanning Within Tables

By default, anything you place inside a table cell is aligned to the left and vertically centered. Figures 6.1 and 6.2 show this default alignment. However, you can align the contents of table cells both horizontally and vertically with the text-align and vertical-align style properties.

You can apply these alignment attributes to any <tr>, <td>, or <th> tag. Alignment attributes assigned to a <tr> tag apply to all cells in that row. Depending on the size of your table, you can save yourself a considerable amount of time and effort by applying these attributes at the <tr> level and not in each <td> or <th> tag.

The HTML code in Listing 6.3 uses a combination of text alignment styles to apply a default alignment to a row, but it is overridden in a few individual cells. Figure 6.3 shows the result of the code in Listing 6.3.

Figure 6.3 The code in Listing 6.3 shows the use of the colspan attribute and alignment styles.

image

Following are some of the more commonly used vertical-align style property values: top, middle, bottom, text-top, text-bottom, and baseline (for text). These property values give you plenty of flexibility in aligning table data vertically.

Listing 6.3 Alignment, Cell Spacing, Borders, and Background Colors in Tables


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
    <title>Things to Fear</title>
  </head>

  <body>
    <h1>Things to Fear</h1>
    <table border="2" cellpadding="4" cellspacing="2"
    width="100%">
      <tr style="background-color:red;color:white">
        <th colspan="2">Description</th>
        <th>Size</th>
        <th>Weight</th>
        <th>Speed</th>
      </tr>
      <tr style="vertical-align:top">
        <td><img src="handgun.gif" alt=".38 Special"/></td>
        <td style="font-size: 14px;font-weight:bold;
        vertical-align:middle;text-align:center">.38 Special</td>
        <td>Five-inch barrel.</td>
        <td>Twenty ounces.</td>
        <td>Six rounds in four seconds.</td>
      </tr>
      <tr style="vertical-align:top">
        <td><img src="rhino.gif" alt="Rhinoceros" /></td>
        <td style="font-size: 14px;font-weight:bold;
        vertical-align:middle;text-align:center">Rhinoceros</td>
        <td>Twelve feet, horn to tail.</td>
        <td>Up to two tons.</td>
        <td>Thirty-five miles per hour in bursts.</td>
      </tr>
      <tr style="vertical-align:top">
        <td><img src="axeman.gif" alt="Broad Axe" /></td>
        <td style="font-size: 14px;font-weight:bold;
        vertical-align:middle;text-align:center">Broad Axe</td>
        <td>Thirty-inch blade.</td>
        <td>Twelve pounds.</td>
        <td>Sixty miles per hour on impact.</td>
      </tr>
    </table>
  </body>
</html>


At the top of Figure 6.3, a single cell (Description) spans two columns. This is accomplished with the colspan attribute in the <th> tag for that cell. As you might guess, you can also use the rowspan attribute to create a cell that spans more than one row.


Tip

Keeping the structure of rows and columns organized in your mind can be the most difficult part of creating tables with cells that span multiple columns or rows. The tiniest error can often throw the whole thing into disarray. You’ll save yourself time and frustration by sketching your tables on paper before you start writing the HTML to implement them.


Spanning is the process of forcing a cell to stretch across more than one row or column of a table. The colspan attribute causes a cell to span across multiple columns; rowspan has the same effect on rows.

Additionally, text styles are used in the second cell within the Description column to create bold text that is both vertically aligned to the middle and horizontally aligned to the center of the cell.

There are a few tricks in Listing 6.3 that I haven’t explained yet. You can give an entire table—and each individual row or cell in a table—its own background, distinct from any background you might use on the web page itself. You can do this by placing the background-color or background-image style in the <table>, <tr>, <td>, or <th> tag exactly as you would in the <body> tag (see Chapter 8, “Working with Colors, Images, and Multimedia”). To give an entire table a yellow background, for example, you would use <table style="background-color:yellow"> or the equivalent <table style="background-color:#FFFF00">. In Listing 6.3, only the top row has a background color; it uses <tr style="background-color:red;color:white"> to apply a red background across the cells in that row. Additionally, the color style ensures that the text in that row is white.


Note

You will often see alternating row colors in a table. For instance, one row might have a grey background and the next row might have a white background. Alternating row colors helps users read the content of your table more clearly, especially if the table is quite large.


Similar to the background-color style property is the background-image property (not shown in this example), which is used to set an image for a table background. If you wanted to set the image leaves.gif as the background for a table, you would use <table style="background-image:url(leaves.gif)">. Notice that the image file is placed within parentheses and preceded by the word url, which indicates that you are describing where the image file is located.


Note

Although the cellpadding and cellspacing attributes are still allowed in XHTML, a CSS equivalent for them exists in the form of the padding and border-spacing style properties.


Tweaking tables goes beyond just using style properties. As shown in Listing 6.3, you can control the space around the borders of a table with the cellpadding and cellspacing attributes. The cellspacing attribute sets the amount of space (in pixels) between table borders and between table cells themselves. The cellpadding attribute sets the amount of space around the edges of information in the cells, also in pixels. Setting the cellpadding value to 0 causes all the information in the table to align as closely as possible to the table borders, possibly even touching the borders. The cellpadding and cellspacing attributes give you good overall control of the table’s appearance.

Page Layout with Tables

At the beginning of this chapter, I indicated that designers have used tables for page layout and to display tabular information. You will still find many examples of table-based layouts if you peek at another designer’s source code. This method of design grew out of the old (mid-1990s to early 2000s) inconsistencies in browser support for CSS. All browsers supported tables and in generally the same way, so web designers latched on to the table-based method of content creation to achieve the same visual page display across all browsers. However, now that support for CSS is relatively similar across all major browsers, designers can follow the long-standing standards-based recommendation not to use tables for page layout.

The World Wide Web Consortium (W3C), the standards body that oversees the future of the Web, promotes style sheets as the proper way to lay out pages (instead of using tables). Style sheets are ultimately much more powerful than tables, which is why the bulk of this book teaches you how to use style sheets for page layout.

The main reasons for avoiding using tables for layout include the following:

Mixing presentation with content—One of the goals of CSS and standards-compliant web design is to separate the presentation layer from the content layer.

Creating unnecessarily difficult redesigns—To change a table-based layout, you would have to change the table-based layout on every single page of your site (unless it is part of a complicated, dynamically driven site, in which case you would have to undo all the dynamic pieces and remake them).

Accessibility issues—Screen reading software looks to tables for content and will often try to read your layout table as a content table.

Rendering on mobile devices—Table layouts are often not flexible enough to scale downward to small screens (see Chapter 12, “Creating Fixed or Liquid Layouts”).

These are but a few of the issues in table-based web design. For a closer look at some of these issues, see the popular presentation “Why Tables for Layout Is Stupid” at http://www.hotdesign.com/seybold/everything.html.

Summary

In this brief chapter, you learned to arrange text and images into organized arrangements of rows and columns called tables. You learned the three basic tags for creating tables and many optional attributes and styles for controlling the alignment, spacing, and appearance of tables. You also discovered that tables can be used together and nested within one another for an even wider variety of layout options.

Table 6.1 summarizes the tags and attributes covered in this chapter.

Table 6.1 HTML Tags and Attributes Covered in Chapter 6

image
image

Q&A

Q. I made a big table and when I load the page, nothing appears on the page for a long time. Why the wait?

A. Complex tables can take a while to appear on the screen. The web browser has to figure out the size of everything in the table before it can display any part of it. You can speed things up a bit by always including width and height attributes for every graphics image within a table. Using width attributes in the <table> and <td> tags also helps.

Q. Can I put a table within a table?

A. Yes, you can nest tables within other table cells. However, nested tables—especially large ones—take time to load and render properly. Before you create a nested table, think about the content you are placing on the page and ask yourself if it could be displayed using CSS. You might not know all the answers until you finish this book, but here’s a hint: In most cases, the answer will be yes.

Workshop

The workshop contains quiz questions and exercises to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows.

Quiz

1. How would you create a simple two-row, two-column table with a standard border?

2. Expanding on question 1, how would you add 30 pixels of space between the table border and the cells?

3. Continuing with the table you’ve built in questions 1 and 2, how would you make the top-left cell green, the top-right cell red, the bottom-left cell yellow, and the bottom-right cell blue?

Answers

1. Use the following HTML:

<table border="1">
  <tr>
    <td>Top left...</td>
    <td>Top right...</td>
  </tr>
  <tr>
    <td>Bottom left...</td>
    <td>Bottom right...</td>
  </tr>
</table>

2. Add cellspacing="30" to the <table> tag.

3. Add style="background-color:green" to the top left <td> tag, add style="background-color:red" to the top right <td> tag, add style="background-color:yellow" to the bottom left <td> tag, and add style="background-color:blue" to the bottom right <td> tag.

Exercises

• Do you have any pages that have information visitors might be interested in viewing as lists or tables? Use a table to present some tabular information. Make sure each column has its own heading (or perhaps its own graphic). Play around with the various types of alignment and spacing that you have learned in this chapter.

• You will often see alternating row colors in a table, with one row having a grey background and the next a white background. The goal of alternating colors in table rows is so that the individual rows are easier to discern when looking quickly at the table full of data. Create a table with alternating row colors and text colors (if necessary). Although the lesson on colors comes in Chapter 8, you have enough information in this lesson to begin trying out the process.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.172.61