Search the Catalog
HTML: The Definitive Guide, 3rd Edition

HTML: The Definitive Guide, 3rd Edition

By Chuck Musciano & Bill Kennedy
3rd Edition August 1998
1-56592-492-4, Order Number: 4924
576 pages, $32.95

Sample Chapter 5: Rules, Images, and Multimedia


In this Chapter:
Horizontal Rules
Inserting Images in Your Documents
Document Colors and Background Images
Background Audio
Animated Text
Other Multimedia Content

While the body of most HTML documents is text, an appropriate seasoning of horizontal rules, images, and other multimedia elements make for a much more inviting and attractive document. These features of HTML are not simply gratuitous geegaws that make your documents look pretty, mind you. Multimedia elements bring HTML documents alive, providing a dimension of valuable information often unavailable in other media, such as print. In this chapter, we describe in detail how you can insert special multimedia elements into your documents, when their use is appropriate, and how to avoid overdoing it.

You also might want to jump ahead and skim Chapter 13, Executable Content. There we describe some catch-all tags, the HTML 4.0 standard <object> and Netscape's <embed>, which let you insert all kinds of content and data file types, including multimedia, into your documents.

Horizontal Rules

Horizontal rules give you a way to separate sections of your document visually. That way, you give readers a clean, consistent, visual indication that one portion of your document has ended and another portion is beginning. Horizontal rules effectively set off small sections of text, delimit document headers and footers, and provide extra visual punch to headings within your document.

The <hr> Tag

The <hr> tag tells the browser to insert a horizontal rule across the display window. Like the <br> tag, <hr> forces a simple line break, although unlike <br>, <hr> causes the paragraph alignment to revert to the default (left-justified). The browser places the rule immediately below the current line, and content flow resumes below the rule.

<hr>

Function:

Break a text flow and insert a horizontal rule

Attributes:

ALIGN
CLASS
COLOR
ID
NOSHADE
NOWRAP
ONCLICK
ONDBLCLICK
ONKEYDOWN
ONKEYPRESS
ONKEYUP
ONMOUSEDOWN
ONMOUSEMOVE
ONMOUSEOUT
ONMOUSEOVER
ONMOUSEUP
SIZE
STYLE
TITLE
WIDTH

End tag:

None

Contains:

Nothing

Used in:

body_content

The rendering of a horizontal rule is at the discretion of the browser. Typically, it extends across the entire document. Graphical browsers may render the rule with a chiseled or embossed effect; character-based browsers most likely use dashes or underscores to create the rule.

<hr>

There is no additional space above or below a horizontal rule. If you wish to set it off from the surrounding text, you must explicitly place the rule in a new paragraph, followed by another paragraph containing the subsequent text. For example, note the spacing around the horizontal rules in the following source and in Figure 5-1 :

This text is directly above the rule.
<hr>
And this text is immediately below. 
<p>
Whereas this text will have space before the rule.
<p>
<hr>
<p>
And this text has space after the rule.

A paragraph tag following the rule tag is necessary if you want the content beneath the rule line aligned in any style other than the default left.

 

Figure 5-1. Paragraph tags give your text extra elbow room

 

The size attribute

Normally, browsers render horizontal rules three pixels 1 thick with a chiseled, 3D appearance, making the rule look incised into the page. You may thicken the rules with the size attribute. The required value is the thickness, in pixels. You can see the effects of this attribute in Figure 5-2 as constructed from the following source:

<p>
This is conventional document text, 
followed by a normal, 3-pixel tall rule line.
<hr>
The next three rule lines are 12, 36, and 72 pixels tall.
<hr size=12>
<hr size=36>
<hr size=72>

The size attribute is deprecated in HTML 4.0, since its effects can be achieved with appropriate use of style sheets.

 

Figure 5-2. Netscape lets you vary the horizontal rule size

 

The noshade attribute

You may not want a 3D rule line, preferring a flat, 2D rule. Just add the noshade attribute (no value required) to the <hr> tag to eliminate the effect. Note the difference in appearance of a "normal" 3D rule versus the noshade 2D one in Figure 5-3. (We've also exaggerated the rule's thickness for obvious effect, as evident in the source HTML fragment.)

<hr size=32>

<hr size=32 noshade>

The noshade attribute is deprecated in HTML 4.0, since its effects can be achieved with appropriate use of style sheets.

 

Figure 5-3. Netscape's 3D rule versus the noshade 2D option

 

The width attribute

The default rule is drawn across the full width of the view window. You can shorten or lengthen rules with the width attribute, creating rule lines that are either an absolute number of pixels wide or extend across a certain percentage of the current text flow. Most browsers automatically center partial-width rules; see the align attribute (section 5.1.1.4) to left- or right-justify horizontal rules.

Here are some examples of width -specified horizontal rules (see Figure 5-4 ):

The following rules are 40 and 320 pixels wide
no matter the actual width of the browser window
<hr width=40>
<hr width=320>
Whereas these next two rules will always extend across
10 and 75 percent of the window, regardless of its width: 
<hr width="10%">

<hr width="75%">

 

Figure 5-4. Absolute versus relative rule widths

 

Notice, too, that the relative (percentage) value for the width attribute is enclosed in quotation marks; the absolute (integer) pixel value is not. In fact, the quotation marks aren't absolutely necessary, but since the percent symbol normally means that an encoded character follows, failure to enclose the percent width value in quotation marks may confuse other browsers and trash a portion of your rendered document.

In general, it isn't a good idea to specify the width of a rule as an exact number of pixels. Browser windows vary greatly in their width, and what might be a small rule on one browser might be annoyingly large on another. For this reason, we recommend specifying rule width as a percentage of the window width. That way, when the width of the browser window changes, the rules retain their same relative size.

The width attribute is deprecated in HTML 4.0, since its effects can be achieved with appropriate use of style sheets.

The align attribute

The align attribute for a horizontal rule can have one of three values: left, center, or right. For those rules whose width is less than the current text flow, the rule will be positioned relative to the window margins accordingly. The default alignment is center.

A varied rule alignment makes for nice section dividers. For example, the source shown below alternates a 35 percent-wide rule from right to center to the left margin (see Figure 5-5 ):

<hr width="35%" align=right>
<h3>Fruit Packing Advice</h3>
... 
<hr width="35%" align=center>
<h3>Shipping Kumquats</h3>
...
<hr width="35%" align=left>
<h3>Juice Processing</h3>
...

The align attribute is deprecated in HTML 4.0, since its effects can be achieved with appropriate use of style sheets.

 

Figure 5-5. Varying horizontal rule alignment makes for subtle section dividers

 

The color attribute

Supported only by Internet Explorer, the color attribute lets you set the color of the rule line. The value of this attribute is either the name of a color or a hexadecimal triple defining a specific color. For a complete list of color names and values, see Appendix F, Color Names and Values.

By default, a rule is set to the same color as the document background, with the chiseled edges slightly darker and lighter than the background color. You lose the 3D effect when you specify another color, either in a style sheet or with the color attribute.

Combining rule attributes

You may combine the various rule attributes; their order isn't important. To create big squares, for example, combine the size and width attributes (see Figure 5-6 ):

<hr size=32 width="50%" align=center>

In fact, some combinations of rule attributes are necessary--align and width, for example. Align alone appears to do nothing because the default rule width stretches all the way across the display window.

 

Figure 5-6. Combining rule attributes for special effects

 

The class, dir, event, id, lang, style, and title attributes

There are several nearly universal attributes for the many HTML content tags. These attributes give you a common way to identify (title ) and label (id ) a tag's contents for later reference or automated treatment; to change the contents' display characteristics (class, style ); and to reference the language (lang ) used and related direction the text should flow (dir ). Of course, how language and the direction of text affect a horizontal rule is unclear. Nonetheless, they are standard attributes for the tag.

In addition, there are all the user events that may happen in and around the horizontal rule that the browser senses and that you may react to via an on-event attribute and some programming.

Using Rules to Divide Your Document

Horizontal rules provide a handy visual navigation device for your readers. To use <hr> effectively as a section divider, first determine how many levels of headings your document has and how long you expect each section of the document to be. Then decide which of your headings warrant being set apart by a rule.

A horizontal rule can also delimit the front matter of a document, separating the table of contents from the document body, for example. Use a rule also to separate the document body from a trailing index, bibliography, or list of figures.

Experienced HTML authors also use horizontal rules to mark the beginning and end of a form. This is especially handy for long forms that make users scroll up and down the page to view all the fields. By consistently marking the beginning and end of a form with a rule, you help users stay within the form, better ensuring they won't inadvertently miss a portion when filling out its contents.

Using Rules in Headers and Footers

A fundamental style approach to HTML document families is to have a consistent look and feel, including a standard header and footer for each document. Typically, the header contains navigational tools that help users easily jump to internal sections as well as related documents in the family, while the footer contains author and document information as well as feedback mechanisms like an email link to the webmaster.

To ensure that these headers and footers don't infringe on the main document contents, consider using rules directly below the header and above the footer. For example (see also Figure 5-7 ):

<body>
Kumquat Growers Handbook - Growing Season Guidelines
<hr>
<h1>Growing Season Guidelines</h1>
Growing season for the noble fruit varies throughout the
United States, as shown in the following map:
<p>
<img src="pics/growing-season.gif">
<p>
<hr>
<i>Provided as a public service by the 

<a href="feedback.html">Kumquat Lovers of America</a></i>

 

Figure 5-7. Clearly delineate headers and footers with horizontal rules

 

By consistently setting apart your headers and footers using rules, you help users locate and focus upon the main body of your document.

Inserting Images in Your Documents

One of the most compelling features of HTML is its ability to include images with your document text, either as an intrinsic component of the document (inline images), as separate documents specially selected for download via hyperlinks, or as a background for your document. When judiciously added to the body content, images--static and animated icons, pictures, illustrations, drawings, and so on--can make your documents more attractive, inviting, and professional looking, as well as informative and easier to browse. You may also specially enable an image so that it becomes a visual map of hyperlinks. When used to excess, however, images make your document cluttered, confusing, and inaccessible, as well as unnecessarily lengthening the time it takes for users to download and view your pages.

image formats

Understanding Image Formats

The HTML standard does not prescribe an official format for images. However, the popular browsers specifically accommodate only certain image formats: GIF and JPEG, in particular (see following sections for explanations). Most other multimedia formats require special accessory applications that each browser owner must obtain, install, and successfully operate to view the special files. So it's not too surprising that GIF and JPEG are the de facto image standards on the Web.

Both image formats were already in widespread use before the Web came into being, so there's lots of supporting software out there to help you prepare your graphics for either format. However, each has its own advantages and drawbacks, including features that some browsers exploit for special display effects.

GIF

The Graphics Interchange Format (GIF) was first developed for image transfer among users of the CompuServe online service. The format has several features that make it popular for use in HTML documents. Its encoding is cross-platform, so that with appropriate GIF decoding software (included with most browsers), the graphics you create and make into a GIF file on a Macintosh, for example, can be loaded into a Windows-based PC, decoded, and viewed without a lot of fuss. The second main feature is that GIF uses special compression technology that can significantly reduce the size of the image file for faster transfer over a network. GIF compression is "lossless," too; none of an image's original data is altered or deleted, so the uncompressed and decoded image exactly matches its original. And GIF images can be easily animated.

Even though GIF image files invariably have the .gif (or .GIF ) filename suffix, there actually are two GIF versions: the original GIF87 and an expanded GIF89a, which supports several new features, including transparent backgrounds, interlaced storage, and animation, that are popular with HTML authors (see section 5.2.1.2). The currently popular browsers support both GIF versions, which use the same encoding scheme that maps 8-bit pixel values to a color table, for a maximum of 256 colors per image. Most GIF images have even fewer colors; there are special tools to simplify the colors in more elaborate graphics. By simplifying the GIF images, you create a smaller color map and enhance pixel redundancy for better file compression and consequently faster downloading.

However, because of the limited number of colors, a GIF-encoded image is not always appropriate, particularly for photorealistic pictures (see JPEG discussion in section 5.2.1.3). Rather, GIFs make excellent icons, reduced color images, and drawings.

Because most graphical browsers explicitly support the GIF format, it is currently the most widely accepted image-encoding format on the Web. It is acceptable for both inline images and externally linked ones. When in doubt as to which image format to use, choose GIF. 2 It will work in almost any situation.

Interlacing, transparency, and animation

GIF images can be made to perform three special tricks: interlacing, transparency, and animation. With interlacing, a GIF image seemingly materializes on the display, rather than progressively flowing onto it from top to bottom. Normally, a GIF encoded image is a sequence of pixel data, in order row-by-row, from top to bottom of the image. While the common GIF image renders onscreen like pulling down a window shade, interlaced GIFs open like a venetian blind. That's because interlacing sequences every fourth row of the image. Users get to see a full image--top to bottom, albeit fuzzy--in a quarter of the time it takes to download and display the remainder of the image. The resulting quarter-done image usually is clear enough so that users with slow network connections can evaluate whether to take the time to download the remainder of the image file.

Not all graphical browsers, although able to display an interlaced GIF, are actually able to display the materializing effects of interlacing. With those that do, users still can defeat the effect by choosing to delay image display until after download and decoding. Older browsers, on the other hand, always download and decode images before display, and don't support the effect at all.

Another popular effect available with GIF images--GIF89a-formatted images, actually--is the ability to make a portion of them transparent so that what's underneath--usually the browser window's background--shows through. The transparent GIF image has one color in its color map designated as the background color. The browser simply ignores any pixel in the image that uses that background color, thereby letting the display window's background show through. By carefully cropping its dimensions and by using a solid, contiguous background color, a transparent image can be made to seamlessly meld into a page's surrounding content or float above it.

Transparent GIF images are great for any graphic you want to meld into the document and not stand out as a rectangular block. Transparent GIF logos are very popular, as are transparent icons and dingbats--any graphic that should appear to have an arbitrary, natural shape. You may also insert a transparent image inline with conventional text to act as a special character glyph within conventional text.

The downside to transparency is that the GIF image will look lousy if you don't remove its border when it is included in a hyperlink anchor (<a> tag ), or is otherwise specially framed. And content flow happens around the image's rectangular dimensions, not adjacent to its apparent shape. That can lead to unnecessarily isolated images or odd-looking sections in your HTML pages.

The third unique trick available to the HTML author with GIF89a-formatted images is the ability to do simple frame-by-frame animation. Using special GIF animation software utilities, you may prepare a single GIF89a file to contain a series of GIF images. The browser displays each image in the file, one after the other, something like the page-flipping animation booklets we had (even drew!) as kids. Special control segments between each image in the GIF file let you set the number of times the browser runs through the complete sequence (looping), how long to pause between each image, whether the image space gets wiped to background before the browser displays the next image, and so on. By combining these control features with those normally available for GIF images, including individual color tables, transparency, and interlacing, you can create some very appealing and elaborate animations. 3

Although simple, GIF animation is powerful for one other important reason: You don't need to specially program your HTML documents to achieve animation. But there is one major downside that limits their use except for small, icon-sized, or thin bands of space in the browser window: GIF animation files get large fast, even if you are careful not to repeat static portions of the image in successive animation cells. And if you have several animations in one document, download delays may--and usually will--annoy the user. If there is any feature on your HTML that deserves close scrutiny for excess, it's GIF animation.

Any and all GIF tricks--interlacing, transparency, and animation--don't just happen; you need special software to prepare the GIF file. Many image tools now save your creations or acquired images in GIF format, and most now let you enable transparency, as well as let you make interlaced GIF files. There also are a slew of shareware and freeware programs specialized for these tasks, as well as for creating GIF animation. Look into your favorite Internet software archives for GIF graphics and conversion tools and also see Chapter 15, Tips, Tricks, and Hacks, for details on creating transparent images.

JPEG

The Joint Photographic Experts Group (JPEG) is a standards body that developed what is now known as the JPEG image-encoding format. Like GIFs, JPEG images are platform-independent and specially compressed for high-speed transfer via digital communication technologies. Unlike GIF, JPEG supports tens of thousands of colors for more detailed, photorealistic digital images. And JPEG uses special algorithms that yield much higher data-compression ratios. It is not uncommon, for example, for a 200-kilobyte GIF image to be reduced to a 30-kilobyte JPEG image. To achieve that amazing compression, JPEG does lose some image data. However, you can adjust the degree of "lossiness" with special JPEG tools, so that although the uncompressed image may not exactly match the original, it will be close enough that most people cannot tell the difference.

Although JPEG is an excellent choice for photographs, it's not a particularly good choice for illustrations. The algorithms used for compressing and uncompressing the image leave noticeable artifacts when dealing with large areas of one color. Therefore, if you're trying to display a drawing, the GIF format may be preferable.

The JPEG format, usually designated by the .jpg (or .JPG ) filename suffix, is nearly universally understood by today's graphical browsers. On rare occasions, you'll come across an older browser that cannot directly display JPEG images.

When to Use Images

Most pictures are worth a thousand words. But don't forget that no one pays attention to a blabbermouth. First and foremost, think of your HTML document images as visual tools, not gratuitous trappings. They should support your text content and help readers navigate your documents. Use images to clarify, illustrate, or exemplify the contents. Content supporting photographs, charts, graphs, maps, and drawings are all natural candidates for appropriate HTML images. Product photographs are essential components in online catalogs and shopping guides, for example. And link-enabled icons and dingbats, including animated images, can be effective visual guides to internal and external resources. If an image doesn't do any of these valuable services for your document, throw it out already!

One of the most important considerations when adding images to a document is the additional delay they add to the retrieval time for a document over the network, particularly for modem connections. While a simple text document might run, at most, 10 or 15 thousand bytes, images can easily extend to hundreds of thousands of bytes each. And the total retrieval time for a document is not only equal to the sum of all its component parts, but also to compounded networking overhead delays since each image requires a separate connection and download request between the client browser and the web server. Depending on the speed of the connection (bandwidth, usually expressed as bits or bytes per second) as well as network congestion that can delay connections, a single document containing one 100-kilobyte image may take anywhere from around 15 seconds through a 57.6 kilobit-per-second modem connection in the wee hours of the morning when most everyone else is asleep, to well over ten minutes with a 9600 bit-per-second modem at noontime. You get the picture?

When to Use Text

Text hasn't gone out of style. For some users, it is the only portion of your document they can access. We argue that, in most circumstances, your documents should be usable by readers who cannot view images or have disabled their automatic download in their browser to improve their low-speed connection. While the urge to add images to all of your documents may be strong, there are times when pure text documents make more sense.

Documents being converted to the Web from other formats rarely have embedded images. Reference materials and other serious content often is completely usable in a text-only form.

You should create text-only documents when access speed is critical and potentially slow. If you know that many users will have only low-speed connections to your pages, you should accommodate them by avoiding the use of images within your documents. Better yet, provide a home (leading) page that lets readers decide between duplicate collections of your work: one containing the images, and another stripped of them. (The popular browsers include special picture icons as place holders for yet-to-be downloaded images, which can trash and muddle your document's layout into an unreadable mess.)

Text is most appropriate--supporting images only, without frills or nonessential graphics--if your documents are to be readily searchable by any of the many web indexing services. Images are almost always ignored by these search engines. If the major content of your pages is provided with images, very little information about your documents will find its way into the online web directories.

Speeding Image Downloads

There are several ways to ameliorate the overhead and delays inherent with images, besides being very choosy about which to include in your documents:

Keep it simple

A full-screen, 24-bit color graphic, even when reduced in size by digital compression with one of the standard formats like GIF or JPEG, is still going to be a network bandwidth hog. Acquire and use the various image management tools to optimize image dimensions and number of colors into the fewest number of pixels. Simplify your drawings. Stay away from panoramic photographs. Avoid large empty backgrounds in your images, as well as gratuitous borders and other space-consuming elements. Also avoid dithering (blending two colors among adjacent pixels to achieve a third color); the technique can significantly reduce the compressibility of your images. Strive for large areas of uniform colors, which compress readily in both GIF and JPEG format.

Reuse images

This is particularly true for icons and GIF animations. Most browsers cache incoming document components in local storage for the very purpose of quick, network connection-less retrieval of data. For smaller GIF animation files, try to prepare each successive image to update only portions that change in the animation, rather than redraw the entire image (this speeds up the animation, too).

Divide up large documents

This is a general rule that includes images. Many small document segments, organized through hyperlinks (of course!) and effective tables of contents tend to be better accepted by users than a few large documents. In general, people would rather "flip" several pages than dawdle waiting for a large one to download. (It's related to the TV channel-surfing syndrome.) One accepted rule of thumb is to keep your documents under 50 kilobytes each, so even the slowest connections won't overly frustrate your readers.

Isolate necessarily large graphics

Provide a special link to large images, perhaps one that includes a thumbnail of the graphic, thereby letting readers decide if and when they want to spend the time downloading the full image. And since the downloaded image isn't mixed with other document components like inline images, it's much easier for the reader to identify and save the image on their system's local storage for later study. (For details on non-inline image downloads, see section Referencing Audio, Video, and Images.)

Specify image dimensions

Finally, another way to improve performance is by including the image's rectangular height and width information in its tag. By supplying those dimensions, you eliminate the extra steps the extended browsers must take to download, examine, and calculate an image's space in the document. There is a downside to this approach, however, that we explore in section Problems with height and width.

JPEG or GIF?

You may choose to use only JPEG or GIF images in your HTML documents if your sources for images or your software toolset prefers one over the other format. Both are nearly universally supported by today's browsers, so there shouldn't be any user-viewing problems.

Nevertheless, we recommend that you acquire the facilities to create and convert to both formats, to take advantage of their unique capabilities. For instance, use GIF's transparency feature for icons and dingbats. Alternatively, use JPEG for large and colorful images for faster downloading.

 

The <img> Tag

The <img> tag lets you reference and insert a graphic image into the current text flow of your HTML document. There is no implied line or paragraph break before or after the <img> tag, so images can be truly "inline" with text and other content.

<img>

Function:

Inserts an image into a document

Attributes:

ALIGN
ALT
BORDER
CLASS
CONTROLS
DIR
DYNSRC
HEIGHT
HSPACE
ID
ISMAP
LANG
LONGDESC
LOOP
LOWSRC
NAME
ONABORT
ONCLICK
ONDBLCLICK
ONERROR
ONKEYDOWN
ONKEYPRESS
ONKEYUP
ONLOAD
ONMOUSEDOWN
ONMOUSEMOVE
ONMOUSEOUT
ONMOUSEOVER
ONMOUSEUP
SRC
START
STYLE
TITLE
USEMAP
VSPACE
WIDTH

End tag:

None

Contains:

Nothing

Used in:

text

The format of the image itself is not defined by the HTML standard, although the popular graphical browsers support GIF and JPEG images. The HTML standard doesn't specify or restrict the size or dimensions of the image, either. Images may have any number of colors, but how those colors are rendered is highly browser-dependent.

<img>

Image presentation in general is very browser-specific. Images may be ignored by nongraphical browsers. Browsers operating in a constrained environment may modify the image size or complexity. And users, particularly those with slow network connections, may choose to defer image loading altogether. Accordingly, you should make sure your documents make sense and are useful, even if the images are completely removed.

The src attribute

The src attribute for the <img> tag is required (unless you use dynsrc with Internet Explorer-based movies; see section 5.2.7.1). Its value is the image file's URL, either absolute or relative to the HTML document referencing the image. To unclutter their document storage, HTML authors typically collect image files into a separate folder they often name something like "pics" or "images."

For example, this HTML fragment places an image of a famous kumquat packing plant into the narrative text (see Figure 5-8 ):

Here we are, on day 17 of the tour, in front of the kumquat
packing plant:
<p>
<img src="pics/packing_plant.gif">
<p>
What an exciting moment, to see the boxes of fruit moving

In the example, the paragraph (<p> ) tags surrounding the <img> tag cause the browser to render the image by itself with some vertical space after the preceding text and before the trailing text. Text may also abut the image, as we describe in section 5.2.6.4.

 

Figure 5-8. Image integrated with text

 

The lowsrc attribute

To the benefit of users, particularly those with slow Internet connections, Netscape provides the lowsrc companion to the src attribute in the <img> tag as a way to speed up document rendering. The lowsrc attribute's value, like src, is the URL of an image file that the browser loads and displays when it first encounters the <img> tag. Then, when the document has been completely loaded and can be read by the user, Netscape goes back and retrieves the image specified by the src attribute.

Ostensibly, the lowsrc image is a low-resolution, abbreviated version of the final src image that loads faster by comparison to quickly give the reader an idea of its content until the final, higher-resolution image eventually replaces it onscreen. But the lowsrc attribute can also be used for some very special effects.

Netscape uses the lowsrc image's dimensions to reserve space in the document for both the lowsrc and src images, unless you explicitly allocate that space with the height and width attributes described later in this chapter. Hence, if the dimensions of the image specified in the src attribute are different than those for the lowsrc image or your explicitly included height and width values, the src image will be reduced, enlarged, stretched, and/or compressed to fit in the allotted space. Moreover, the lowsrc and src images needn't be identical, so you might take advantage of the delayed rendering of the src image for simple animation.

The lowsrc attribute is for Netscape only. Other browsers ignore it and only load the image specified by the src attribute. Netscape won't load either image if the user chooses not to auto-load images. In that case, both images will load in order when the user clicks the images button or clicks the image icon placeholder. No browser loads the lowsrc image only; you must include a src image, otherwise nothing will appear except the missing image icon.

The alt and longdesc attributes

The alt attribute specifies alternative text the browser may show if image display is not possible or disabled by the user. It's an option, but one we highly recommend you exercise for most images in your document. This way, if the image is not available, the user still has some indication of what it is that's missing.

The value for the alt attribute is a text string of up to 1024 characters, enclosed in quotation marks if you include spaces or other punctuation. The alternative text may contain entity references to special characters, but it may not contain any other sort of markup; in particular, no style tags are allowed.

Graphical browsers ignore the alt attribute if the image is available and downloading is enabled by the user. Otherwise, they insert the alt attribute's text as a label next to an image placeholder icon. Well-chosen alt labels thereby additionally support those users with a graphical browser who have disabled their automatic image download because of a slow connection to the Web.

Nongraphical, text-only browsers like Lynx put the alt text directly into the content flow just like any other text element. So, when used effectively, the alt tag sometimes can transparently substitute for missing images. (Your text-only browser users will appreciate not being constantly reminded of their second-class web citizenship.) For example, consider using an asterisk as the alt attribute alternative to a special bullet icon:

<h3><img src="pics/fancy_bullet.gif" alt="*">Introduction</h3>

A graphical browser displays the bullet image, while in a nongraphical browser the alt asterisk takes the place of the missing bullet. Similarly, use alt text to replace special image bullets for list items. For example, the following code:

<ul>
  <li> Kumquat recipes <img src="pics/new.gif" alt="(New!)">
  <li> Annual harvest dates
</ul>

displays the new.gif image with graphical browsers, and the text "(New!)" with text-only browsers.

The alt attribute lets you use even more complex text (see Figure 5-9 ):

Here we are, on day 17 of the tour, in front of the kumquat
packing plant:
<p>
<img src="pics/packing_plant.gif"
  alt="[Image of our tour group outside the main packing plant]">
<p>

What an exciting moment, to see the boxes of fruit moving

 

Figure 5-9. Text-only browsers like Lynx display an image's alt attribute text

 

The longdesc attribute is similar to the alt attribute, but allows for larger descriptions. The value of longdesc is the URL of a document containing a description of the image. Presumably, if you absolutely must regale the user with a description longer than 1024 characters, use the longdesc attribute to link to that description. HTML 4.0 does not specify what the content of the description must be, nor do any browsers currently implement longdesc, so all bets are off when deciding how to create those long descriptions.

The align attribute

The HTML standard does not define a default alignment for images with respect to other text and images in the same line of text, so you cannot absolutely predict how the mixture of text and images will look. 4 HTML images normally appear in line with a single line of text. Our common media like magazines typically wrap text around images, with several lines next to and abutting the image, not just a single line.

image alignment

Fortunately, HTML document designers can exert some control over the alignment of images with the surrounding text through the align attribute for the <img> tag. The HTML standard specifies five image-alignment attribute values: left, right, top, middle, and bottom. The left and right values flow any subsequent text around the image, which is moved to the corresponding margin; the remaining three align the image vertically with respect to the surrounding text. Netscape adds four more vertical alignment attributes to that list: texttop, absmiddle, baseline, and absbottom, while Internet Explorer adds center.

The following list contains descriptions for the inline HTML image alignments; see Figure 5-10 for examples:

 

Figure 5-10. HTML standard and browser-extended inline image alignments with text

 

top

The top of the image is aligned with the top edge of the tallest item in the current line of text. If there are no other images in the current line, the top of the image is aligned with the top of the text.

texttop

The align=texttop attribute and value tells Netscape to align the top of the image with the top of the tallest text item in the current line. This is slightly different from the standard HTML top option, which aligns the top of the image with the top of the tallest item, image or text, in the current line. If the line contains no other images that extend above the top of the text, texttop and top have the same effect.

middle

Netscape and Internet Explorer treat the middle image alignment value differently: Netscape always aligns the middle of the image to the baseline of the text, regardless of other inline elements, such as another inline image (see Figure 5-11 ). Internet Explorer, on the other hand, aligns the middle of the image to the middle of the tallest item in the current line, text or image (see Figure 5-12 ). Notice the alignments and differences in Figures Figure 5-11 and Figure 5-12, particularly when only one image contains the align attribute. Both figures display the HTML fragment:

Line of text  
<img src="pics/horiz.gif" align=middle>
<img src="pics/vert.gif">
goes on ...
<br clear=left>
<p>
Line of text
<img src="pics/horiz.gif" align=middle>
<img src="pics/vert.gif" align=middle>
goes on ...

Also note that Internet Explorer Version 3 treats middle, absmiddle, and center the same, whereas earlier Internet Explorer versions and the current Netscape (Version 4) distinguish between middle and absmiddle alignments. (If you are confused as to exactly what each alignment value means, please raise your hand.)

 

Figure 5-11. Netscape aligns middle of image to baseline of text

 

 

Figure 5-12. Internet Explorer aligns middle of image to middle of tallest line element

 

absmiddle

If you set the align attribute of the <img> tag to absmiddle, the browser will fit the absolute middle of the image to the absolute middle of the current line. For Netscape and earlier versions of Internet Explorer, this is different from the common middle option, which aligns the middle of the image with the baseline of the current line of text (the bottom of the characters). Version 3 of Internet Explorer, on the other hand, treats absmiddle the same as middle and center.

center

The center image alignment value gets treated the same as absmiddle by both Internet Explorer and Netscape, but note that the browsers treat absmiddle and middle differently.

bottom and baseline (default)

With Netscape and earlier versions of Internet Explorer, the bottom and baseline image alignment values have the same effect as if you didn't include any alignment attribute at all: the browsers align the bottom of the image in the same horizontal plane as the baseline of the text. This is not to be confused with the absbottom, which takes into account letter "descenders" like the tail on the lowercase "y." Internet Explorer Version 3, on the other hand, treats bottom the same as absbottom. (Did we see a hand up in the audience?)

absbottom

The align=absbottom attribute tells the browsers to align the bottom of the image with the true bottom of the current line of text. The true bottom is the lowest point in the text taking into account descenders, even if there are no descenders in the line. A descender is the tail on a "y," for example; the baseline of the text is the bottom of the "v" in the "y" character.

Use the top or middle alignment values for best integration of icons, dingbats, or other special inline effects with the text content. Otherwise, align=bottom (the default) usually gives the best appearance. When aligning one or more images on a single line, select the alignment that gives the best overall appearance to your document.

Wrapping text around images

The left and right image alignment values tell the browser to place an image against the left or right margin, respectively, of the current text flow. The browser then renders subsequent document content in the remaining portion of the flow adjacent to the image. The net result is that the document content following the image gets wrapped around the image.

<img src="pics/kumquat.gif" align=left>
The kumquat is the smallest of the citrus fruits, similar in appearance 
to a tiny orange. The similarity ends with its appearance, however. 
While oranges are generally sweet, kumquats are extremely bitter. 
Theirs is an acquired taste, to be sure.

Figure 5-13 shows text flow around a left-aligned image.

 

Figure 5-13. Text flow around a left-aligned image

 

You can place images against both margins simultaneously (Figure 5-14 ) and the text will run down the middle of the page between them:

<img src="pics/kumquat.gif" align=left>
<img src="pics/tree.gif" align=right>
The kumquat is the smallest of the citrus fruits, similar in appearance 
to a tiny orange. The similarity ends with its appearance, however. 
While oranges are generally sweet, kumquats are extremely bitter. 
Theirs is an acquired taste, to be sure.

 

Figure 5-14. Running text between left- and right-aligned images

 

While text is flowing around an image, the left (or right) margin of the page is temporarily redefined to be adjacent to the image as opposed to the edge of the page. This means that subsequent images with the same alignment will stack up against each other. The following source fragment achieves that staggered image effect:

<img src="pics/marcia.gif" align=left>
Marcia!
<br>
<img src="pics/jan.gif" align=left>
Jan!
<br>
<img src="pics/cindy.gif" align=left>
Cindy!

The results of this example are shown in Figure 5-15.

 

Figure 5-15. Three very lovely girls

 

When the text flows beyond the bottom of the image, the margin returns to its former position, typically at the edge of the browser window.

Centering an image

Have you noticed that you can't horizontally center an image in the browser window with the align attribute? The middle and absmiddle values center the image vertically with the current line, but the image is horizontally justified depending on what content comes before it in the current flow and the dimensions of the browser window.

You can horizontally center an inline image in the browser window, but only if it's isolated from surrounding content, such as by paragraph, division, or line break tags. Then, either use the <center> tag, or use the align=center attribute or center-justified style in the paragraph or division tag to center the image. For example:

Kumquats are tasty treats
<br>
<center>
<img src="pics/kumquat.gif"> 
</center>
that everyone should strive to eat!

Use the paragraph tag with its align=center attribute if you want some extra space above and below the centered image:

Kumquats are tasty treats
<p align=center>
<img src="pics/kumquat.gif"> 
</p>
that everyone should strive to eat!

Align is deprecated

The HTML 4.0 standard has deprecated the align attribute for all tags, including <img>, in deference to style sheets. Nonetheless, the attribute is very popular among HTML authors, and remains very well supported by the popular browsers. So, while we do expect that someday align will disappear, it won't be anytime soon. Just don't say we didn't warn you.

The border attribute

Browsers normally render images that also are hyperlinks (included in an <a> tag) with a two-pixel-wide colored border, indicating to the reader that the image can be selected to visit the associated document. Use the border attribute and a pixel-width thickness value to remove (border=0 ) or widen that image border. Be aware that this attribute, too, is deprecated in HTML 4.0 in lieu of style sheets, but continues to be well supported by the popular browsers.

border attribute

Figure 5-16 shows you the thick and thin of image borders, as rendered from the following HTML source:

<a href="test.html">
 <img src="pics/kumquat.gif" border=1>
</a>
<a href="test.html">
  <img src="pics/kumquat.gif" border=2>
</a>
<a href="test.html">
  <img src="pics/kumquat.gif" border=4>
</a>
<a href="test.html">
  <img src="pics/kumquat.gif" border=8>

</a>

 

Figure 5-16. The thick and thin of image borders

 

Removing the image border

You can eliminate the border around an image hyperlink altogether with the border=0 attribute within the <img> tag. For some images, particularly image maps, the absence of a border can greatly improve the appearance of your pages. Images that are clearly link buttons to other pages may also look best without a border.

Be careful, though, that by removing the border, you don't diminish your page's usability. No border means you've removed a common visual indicator of a link, making it less easy for your readers to find the links on the page. Browsers will change the mouse cursor as readers pass it over an image that is a hyperlink, but you should not assume they will, nor should you make readers test your borderless images to find hidden links.

We strongly recommend that you use some additional way with borderless images to let your readers know to click the images. Even including simple text instructions will go a long way to making your pages more accessible to readers.

The height and width attributes

Ever watch the display of a page's contents shift around erratically while the document is loading? That happens because the browser readjusts the page layout to accommodate each loaded image. The browser determines the size of an image and, hence, the rectangular space to reserve for it in the display window, by retrieving the image file and extracting its embedded height and width specifications. The browser then adjusts the page's display layout to insert that picture in the display. This is not the most efficient way to render a document, since the browser must sequentially examine each image file and calculate its screen space before rendering adjacent and subsequent document content. That can significantly increase the amount of time it takes to render the document and disrupt reading by the user.

height and width attributes

A more efficient way for HTML authors to specify an image's dimensions is with the height and width <img> attributes. That way, the browser can reserve space before actually downloading an image, speeding document rendering and eliminating the content shifting. Both attributes require an integer value that indicates the image size in pixels; the order in which they appear in the <img> tag is not important.

Resizing and flood-filling images

A hidden feature of the height and width attributes is that you don't need to specify the actual image dimensions; the attribute values can be larger or smaller than the actual size of the image. The browser automatically scales the image to fit the predefined space. This gives you a down-and-dirty way of creating thumbnail versions of large images and a way to enlarge very small pictures. Be careful, though: the browser still must download the entire file, no matter what its final rendered size is, and you will distort an image if you don't retain its original height versus width proportions.

Another trick with height and width provides an easy way to flood-fill areas of your page and can also improve document performance. Suppose you want to insert a colored bar across your document. 5 Rather than create an image to the full dimensions, create one that is just one pixel high and wide and set it to the desired color. Then use the height and width attributes to scale it to the larger size:

<img src="pics/one-pixel.gif" width=640 height=20>

The smaller image downloads much faster than a full-scale image, and the width and height attributes create the desired bar after the tiny image arrives at the browser (see Figure 5-17 ).

 

Figure 5-17. This bar was made from a one-pixel image

 

One last trick with the width attribute is to use a percentage value instead of an absolute pixel value. This causes the browser to scale the image to a percentage of the document window width. Thus, to create a colored bar 20 pixels high and the width of the window, you could use:

<img src="pics/one-pixel.gif" width="100%" height=20>

As the document window changes size, the image will change size as well.

If you provide a percentage width and omit the height, the browser will retain the image's aspect ratio as it grows and shrinks. This means that the height will always be in the correct proportion to the width and the image will display without distortion.

Problems with height and width

Although the height and width attributes for the <img> tag can improve performance and let you perform some neat tricks, there is a particularly knotty downside to using them. The browser sets aside the specified rectangle of space to the prescribed dimensions in the display window even if the user has turned off automatic download of images. What the user often is left with is a page full of semi-empty frames with meaningless picture placeholder icons inside. The page looks terribly unfinished and is mostly useless. Without accompanying dimensions, on the other hand, the browser simply inserts a placeholder icon inline with the surrounding text, so at least there's something there to read in the display.

We don't have an answer to this dilemma, other than to insist that you use the alt attribute with some descriptive text so that users at least know what they are missing (see section 5.2.6.3). We do recommend that you include these size attributes, because we encourage any practice that improves network performance.

The hspace and vspace attributes

Graphical browsers usually don't give you much space between an image and the text around it. And unless you create a transparent image border that expands the space between them, the typical two-pixel buffer between an image and adjacent text is just too close for most designers' comfort. Add the image into a hyperlink, and the special colored border will negate any transparent buffer space you labored to create, as well as draw even more attention to how close the adjacent text butts up against the image.

The hspace and vspace attributes can give your images breathing room. With hspace, you specify the number of pixels of extra space to leave between the image and text on the left and right sides of the image; the vspace value is the number of pixels on the top and bottom:

<img src="pics/kumquat.gif" align=left>
The kumquat is the smallest of the citrus fruits, similar
in appearance to a tiny orange. The similarity ends with its
appearance, however. While oranges are generally sweet,
kumquats are extremely bitter. Theirs is an acquired taste,
to be sure. Most folks, at first taste, wonder how you could 
ever eat another, let alone enjoy it!
<p>
<img src="pics/kumquat.gif" align=left hspace=10 vspace=10>
The kumquat is the smallest of the citrus fruits, similar
in appearance to a tiny orange. The similarity ends with its
appearance, however. While oranges are generally sweet,
kumquats are extremely bitter. Theirs is an acquired taste,
to be sure. Most folks, at first taste, wonder how you could 
ever eat another, let alone enjoy it!

Figure 5-18 shows the difference between two wrapped images.

 

Figure 5-18. Improve image/text interfaces with vspace and hspace extensions

 

We're sure you'll agree that the additional space around the image makes the text easier to read and the overall page more attractive.

The ismap and usemap attributes

The ismap and usemap attributes for the <img> tag tell the browser that the image is a special mouse-selectable visual map of one or more hyperlinks, commonly known as an image map. The ismap style of image maps, known as a server-side image map, may be specified only within an <a> tag hyperlink.

usemap

For example:

<a href="/cgi-bin/images/map2"> 
  <img src="pics/map2.gif" ismap>
</a>

The browser automatically sends the x,y position of the mouse (relative to the upper-left corner of the image) to the server when the user clicks somewhere on the ismap image. Special server software (the /cgi-bin/images/map2 program in the example) may then use those coordinates to determine a response.

The usemap attribute provides a client-side image map mechanism that effectively eliminates server-side processing of the mouse coordinates and its incumbent network delays and problems. Using special <map> and <area> tags, HTML authors provide a map of coordinates for the hyperlink-sensitive regions in the usemap image along with related hyperlink URLs. The value of the usemap attribute is a URL that points to that special <map> section. The browser on the user's computer translates the coordinates of a click of the mouse on the image into some action, including loading and displaying another document.

For example, the following source specially encodes the 100 ¥ 100-pixel map2.gif image into four segments, each of which, if clicked by the user, links to a different document. Also notice that we've included, validly, the ismap image map processing capability in the example <img> tag so that users of other, usemap -incapable browsers have access to the alternative, server-side mechanism to process the image map:

<a href="/cgi-bin/images/map2">
  <img src="pics/map2.gif" ismap usemap="#map2">
</a>
... 
<map name="map2">
  <area coords="0,0,49,49" href="link1.html"> 
  <area coords="50,0,99,49" href="link2.html"> 
  <area coords="0,50,49,99" href="link3.html"> 
  <area coords="50,50,99,99" href="link4.html"> 
</map>

Geographical maps make excellent ismap and usemap examples: browsing a nationwide company's pages, for instance, the user might click on his or her home town on a map to get the addresses and phone numbers for nearby retail outlets. The advantage of the usemap client-side image map processing is that it does not require a server or special server software and so, unlike the ismap mechanism, can be used in non-web (networkless) environments, such as local files or CD-ROM.

Please read our more complete discussion of anchors and links, including image maps within links, in section 7.5.

The class, dir, event, id, lang, style, and title attributes

Several nearly universal attributes give you a common way to identify (title ) and label (id ) the image tag's contents for later reference or automated treatment; to change the contents' display characteristics (class, style ); and to reference the language (lang ) used and related direction the text should flow (dir ). And, of course, there are all the user events that may happen in and around the tagged contents that the browsers senses and that you may react to via an on-event attribute and some programming.

Of these many HTML 4.0 attributes, id is the most important. It lets you label the image for later access by a program or browser operation (see Chapter 13 ).

The remaining attributes have questionable meaning in context with <img>. Granted, there are a few style sheet options that may influence an image's display, and a title is good to include, although alt is better. And it's hard to imagine what the influence of language (lang ) or its presentation direction (dir ) might have on an image.

The name, onAbort, onError, onLoad and other event attributes

There are four <img> attributes currently supported by Netscape that enables you to use JavaScript to manipulate the image. The first is the name attribute. Now redundant with the HTML 4.0 standard id attribute, name lets you label the image so that it can be referenced by a JavaScript applet. For example:

<img src="pics/kumquat.gif" name="kumquat">

lets you later refer to that picture of a kumquat as simply "kumquat" in a JavaScript applet perhaps to erase or otherwise modify it. You cannot individually manipulate an image with JavaScript if it is not named or doesn't have an associated id.

The other three attributes let you provide some special JavaScript event handlers. The value of the attribute is a chunk of JavaScript code, enclosed in quotation marks; it may consist of one or more JavaScript expressions, separated by semicolons.

Netscape invokes the onAbort event handler if the user stops loading an image, usually by clicking the browser's "stop" button. You might, for instance, use an onAbort message to warn users if they stop loading some essential image, such as an image map (see section 6.5):

<img src="pics/kumquat.gif" usemap="#map1" onAbort="window.alert"('Caution: This image contains important
   hyperlinks. Please load the entire image.')">

The onError attribute is invoked if some error occurs during the loading of the image, but not for a missing image or one that the user chose to stop loading. Presumably, the applet could attempt to recover from the error or load a different image in its place.

Netscape executes the JavaScript code associated with the <img> tag's onLoad attribute right after the browser successfully loads and displays the image.

See section 13.3.3 for more information about JavaScript and event handlers.

Combining <img> attributes

You may combine any of the various standard and extension attributes for images where and when they make sense. The order for inclusion of multiple attributes in the <img> tag is not important, either. Just be careful not to use redundant attributes or you won't be able to predict the outcome.

Video Extensions

The special controls, dynsrc, loop, and start attribute extensions for the <img> tag are unique to Internet Explorer and are not HTML 4.0 standard attributes. They let you embed an inline movie into the body content, just like an image.

Equivalent behavior is available in Netscape via an extension program known as a plug-in. Plug-ins place an additional burden on the user, in that each user must find and install the appropriate plug-in before being able to view the inline video. The Internet Explorer <img> tag extensions, on the other hand, make video display an intrinsic part of the browser.

However, the Internet Explorer movie extensions currently are very limited. They are not supported by any other browser and can be used only with Audio Video Interleave ( AVI) formatted movie files, since that's the player format built into Internet Explorer and enabled through Microsoft's Windows operating system software. Moreover, recent innovations in browser technology, objects, and applets in particular, may make Internet Explorer's approach of extending the already overloaded <img> tag obsolete.

The dynsrc attribute

Use the dynsrc attribute extension in the <img> tag to reference an AVI movie for inline display by Internet Explorer. Its required value is the URL of the movie file enclosed in quotation marks. For example, this text displays the tag and attribute for an AVI movie file entitled intro.avi :

<img dynsrc="movies/intro.avi">

The browser sets aside a video viewport in the HTML display window and plays the movie, with audio if it's included in the clip and if your computer is able to play audio. Internet Explorer treats dynsrc movies similar to inline images: in line with current body content and according to the dimension of the video frame. And, like common images, the dynsrc referenced movie file gets displayed immediately after download from the server. You may change those defaults and add some user controls with other attributes, as described later.

Because all other browsers currently ignore the special Internet Explorer attributes for movies, they may become confused by an <img> tag that does not contain the otherwise required src attribute and an image URL. We recommend that you include the src attribute and a valid image file URL in all <img> tags, including those that reference a movie for Internet Explorer users. The other browsers display the still image in place of the movie; Internet Explorer does the reverse and plays the movie, but does not display the image. Note that the order of attributes does not matter. For example:

<img dynsrc="movies/intro.avi" src="pics/mvstill.gif">

Internet Explorer loads and plays the AVI movie intro.avi ; other graphical browsers will load and display the mvstill.gif image instead.

The controls attribute

Normally, Internet Explorer plays a movie inside a framed viewport once, without any visible user controls. The user may restart, stop, and continue the movie by clicking inside that viewport with the mouse. Use the controls attribute (no value) to add visible controls to the movie viewport so that the user may, with the mouse, play, fast-forward, reverse, stop, and pause the movie, like on a VCR. If the movie clip includes a sound track, Internet Explorer provides an audio volume control as well. For example:

<img dynsrc="movies/intro.avi" controls src="pics/mvstill.gif">

adds the various playback controls to the video window of the intro.avi movie clip, as shown in Figure 5-19.

 

Figure 5-19. The controls attribute adds movie playback controls to the video playback frame

 

The loop attribute

Internet Explorer normally plays a movie clip from beginning to end once after download. The loop attribute for the movie <img> tag lets you have the clip play repeatedly for an integer number of times set by the attribute's value, or forever if the value is infinite. The user may still cut the loop short by clicking on the movie image, by pressing the stop button, if given controls (see section 5.2.7.2), or by moving on to another document.

The following intro.avi movie clip will play from beginning to end, then restart at the beginning and play through to the end nine more times:

<img dynsrc="movies/intro.avi" loop=10 src="pics/mvstill.gif">

Whereas the following movie will play over and over again, incessantly:

<img dynsrc="movies/intro.avi" loop=infinite src="pics/mvstill.gif">

Looping movies aren't necessarily meant to annoy. Some special effects animations, for instance, are a sequence of repeated frames or segments. Rather than string the redundant segments into one, long movie that extends its download time, simply loop the single, compact segment.

The start attribute

Normally, an Internet Explorer movie clip starts playing as soon as it's downloaded. You can modify that behavior with the start attribute in the movie's <img> tag. By setting its value to mouseover, you delay playback until the user passes the mouse pointer over the movie viewport. The other valid start attribute value, fileopen, is the default: start playback just after download. It is included because both values may be combined in the start attribute to cause the movie to play back automatically once after download, and then whenever the user passes the mouse over its viewport. Add a value-separating comma, with no intervening spaces, or else enclose them in quotes, when combining the start attribute values.

For example, our by-now-infamous intro.avi movie will play once when its host HTML document is loaded by the user, and whenever he or she passes the mouse over the movie's viewport:

<img dynsrc="movies/intro.avi" start="fileopen,mouseover"
     src="pics/mvstill.gif">

Combining movie <img> attributes

Treat Internet Explorer inline movies as you would any image, mixing and matching the various movie-specific as well as the standard and extended <img> tag attributes and values supported by the browser. For example, you might align the movie (or its image alternative, if displayed by another browser) to the right of the browser window:

<img dynsrc="movies/intro.avi" src="pics/mvstill.gif" align=right>

Combining attributes to achieve a special effect is good. We also recommend you combine attributes to give control to the user, when appropriate. For instance, if you set up a movie to loop incessantly, you should also include the controls attribute so the user can stop the movie without having to leave the HTML document.

As we stated in section 5.2.7.4, by combining attributes you can also delay playback until the user passes the mouse over its viewport. Magically, the movie comes alive and plays continuously:

<img dynsrc="movies/magic.avi" start=mouseover
     loop=infinite src="pics/magic.gif">

Document Colors and Background Images

The HTML 4.0 standard provides a number of attributes for the <body> tag that allow the HTML author to define text, link, and document background colors, in addition to defining an image to be used as the document background. Internet Explorer extends these attributes to include document margins and better background image control. And, of course, the latest style sheet technologies integrated into the current browsers let you manipulate all these various display parameters.

Additions and Extensions to the <body> Tag

The attributes that control the document background, text color, and document margins are used with the <body> tag.

The bgcolor attribute

One standard way you can change the default background color in the browser window to another hue with the bgcolor attribute for the <body> tag. Like the color attribute for the <font> tag, the required value of the bgcolor attribute may be expressed in either of two ways: as the red, green, and blue (RGB) components of the desired color or as a standard color name. Appendix F, Color Names and Values, provides a complete discussion of RGB color encoding along with a table of acceptable color names you can use with the bgcolor attribute.

Setting the background color is easy. To get a pure red background using RGB encoding, try:

<body bgcolor="#FF0000">

For a more subtle background, try:

<body bgcolor=peach>

The background attribute

If a splash of color isn't enough, you may also place an image into the background of a document with the background attribute in its <body> tag.

The required value of the background attribute is the URL of an image. The browser automatically repeats (tiles) the image both horizontally and vertically to fill the entire window.

You normally should choose a small, somewhat dim image to create an interesting but unobtrusive background pattern. Besides, a small, simple image traverses the network much faster than an intricate, full-screen image.

Figure 5-20 shows you how the extended browsers repeatedly render a single brick to create a wall of bricks for the document background:

<body background="pics/onebrick.gif">

 

Figure 5-20. One brick becomes many in a Netscape background

 

Background images of various dimensions and sizes create interesting vertical and horizontal effects on the page. For instance, a tall skinny image might set off your document heading:

<body background="pics/vertical_fountain.gif">
<h3>Kumquat Lore</h3>
For centuries, many myths and legends have arisen around the kumquat.

If the vertical_fountain.gif is a narrow, tall image whose color grows lighter towards its base and whose length exceeds the length of the document body, the resulting document might look like the one shown in Figure 5-21.

 

Figure 5-21. A tall and skinny background

 

You can achieve a similar effect horizontally with an image that is much wider than it is long (see Figure 5-22 ).

bgproperties attribute

 

Figure 5-22. A long and skinny background

 

The background attribute is deprecated in HTML 4.0, since you can achieve similar effects using style sheets.

The bgproperties attribute

The bgproperties attribute extension for the <body> tag is exclusive to Internet Explorer and works only in conjunction with the background attribute extension. The bgproperties attribute has a single value, fixed . It freezes the background image to the browser window, so it does not scroll with the other window contents. Hence, the example H2Omark.gif background image servers as a watermark for the document:

<body background="pics/H2Omark.gif" bgproperties="fixed">

The text attribute

Once you alter a document's background color or add a background image, you also might need to adjust the text color to ensure that users can read the text. The HTML 4.0 text standard attribute for the <body> tag does just that: it sets the color of all nonanchor text in the entire document.

Give the text attribute a color value in the same format as you use to specify a background color (see bgcolor in section 6.3.1.1)--an RGB triplet or color name, as described in Appendix F, Color Names and Values. For example, to produce a document with blue text on a pale yellow background, use:

<body bgcolor="#777700" text="blue">

Of course, it's best to select a text color that contrasts well with your background color or image.

The text attribute is deprecated in HTML 4.0, since you can achieve similar effects using style sheets.

The link, vlink, and alink attributes

The link, vlink, and alink attributes of the <body> tag control the color of hypertext (<a> tag) in your documents. All three accept values that specify a color as an RGB triplet or color name, just like the text and bgcolor attributes.

The link attribute determines the color of all hyperlinks the user has not yet followed. The vlink attribute sets the color of all links the extended browser user had followed at one time or another. The alink attribute defines a color for active link text--one that is currently selected by the user and is under the mouse cursor with the mouse button depressed.

Like text color, you should be careful to select link colors that can be read against the document background. Moreover, the link colors should be different from the regular text as well as from each other.

These attributes are deprecated in HTML 4.0, since you can achieve similar effects using style sheets.

The leftmargin attribute

Peculiar to Internet Explorer, the leftmargin attribute extension for the <body> tag lets you indent the left margin relative to the left edge of the browser's window, much like a margin on a sheet of paper. Other browsers ignore this attribute and normally left-justified body content abuts the left edge of the document window.

The value of the leftmargin attribute is the integer number of pixels for that left-margin indent; a value of 0 is the default. The margin is filled with the background color or image.

For example, Internet Explorer renders the following text justified against a margin 50 pixels away from the left edge of the browser window (see Figure 5-23 ):

<body leftmargin=50>
Internet Explorer lets you indent the<br>
&lt;--left margin<br>
away from the left edge of the window. 

</body>

 

Figure 5-23. Internet Explorer's leftmargin attribute for indenting body content

 

The topmargin attribute

Like leftmargin, the topmargin attribute extension currently is exclusive to Internet Explorer. It may be included in the <body> tag to set a margin of space at the top of the document. The margin space is filled with the document's background color or image.

Body content begins flowing below the integer number of pixels you specify as the value for topmargin ; a value of 0 is the default.

For example, Internet Explorer renders the following text at least 50 pixels down from the top edge of the browser window (see Figure 5-24 ):

<body topmargin=50>
<center>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
</center>
Internet Explorer can give your documents 
a little extra headroom. 

</body>

 

Figure 5-24. Internet Explorer's topmargin attribute for lowering body content

 

The style and class attributes

You also can set all the various style-related <body> features and then some with HTML style sheets. But although you may include the style attribute with the <body> tag to create an inline style for the entire body content, we recommend that you set the styles for the entire document body at the document level (<style> tag inside the document head) or via a collection-level (imported) style sheet. Use the class attribute and name value to apply the appropriate style of a predefined class of the <body> tag to the contents. (Since there can only be one body per document, what is the point of setting a class name otherwise?) We cover the use of style and class definitions in Chapter 9.

Mixing and matching body attributes

Although background and bgcolor attributes can appear in the same <body> tag, a background image will effectively hide the selected background color unless the image contains substantial portions of transparent areas, as we described earlier in this chapter. But even if the image does hide the background color, go ahead and include the bgcolor attribute and some appropriate color value. That's because users can turn off image downloading, which includes background images, and so they may find your page otherwise left naked and unappealing. Moreover, without a bgcolor attribute or a downloaded (for whatever reason) background image, the browsers merrily ignore your text and link color attributes, too, reverting instead to its own default values, or the ones chosen by the user.

Extending a Warning

The various color and image extensions work wonderfully, particularly the colorful ones, assuming that all users have a 256-color display, lots of available memory, unlimited network bandwidth, and good visual acuity. In reality, many users have monochrome or limited color displays, limited memory for caching images, extremely restricted network bandwidth, and poor vision.

Because of these limitations, you should seriously consider not using any of these extensions in your documents. Much like early users of the Macintosh felt compelled to create documents using ransom-note typography ("I've got 40 fonts on this thing, and I'm going to use them all!"), many authors cannot avoid adding some sort of textured background to every document they create ("I've got 13 wood grains and 22 kinds of marbling, and I'm going to use them all!").

In reality, except for the very clever ones, texture-mapped backgrounds add no information to your documents. The value of your document ultimately lies in its text and imagery, not the cheesy blue swirly pattern in the background. No matter how cool it looks, your readers are not benefiting and could be losing readability.

We advise you not to use the color extensions except for comparatively frivolous endeavors or unless the extension really adds to the document's value, such as for business advertising and marketing pages.

Problems with background images

Here are some of the things that can go wrong with background images:

Problems with background, text, and link colors

There also are a slew of problems you will encounter if you play with background colors, including:

And then again

There is no denying the fact that these extensions result in some very stunning HTML documents. And they are fun to explore and play with. So, rather than leave this section on a sour note of caution, we encourage you to go ahead and play--just play carefully.

Background Audio

There is one other form of inline multimedia generally available to web surfers--audio. Most browsers treat audio multimedia as separate documents, downloaded and displayed by special helper applications, applets, or plug-ins. Internet Explorer, on the other hand, contains a built-in sound decoder and supports a special HTML tag that lets you integrate an audio file with your document that plays in the background as a soundtrack for your page.

We applaud the developers of Internet Explorer for providing a mechanism that more cleanly integrates audio into HTML documents. And the possibilities with audio are very enticing. But at the same time, we caution authors that the special tags and attributes for audio don't work with other browsers, and whether this is the method that the majority of browsers will eventually support is not at all assured. So, beware.

The <bgsound> Tag

Use the <bgsound> tag to play a soundtrack in the background. This tag is for Internet Explorer documents only. All other browsers ignore the tag. It downloads and plays an audio file when the host HTML document is first downloaded by the user and displayed in their browser. The background sound file also will replay whenever the user refreshes the browser display.

<bgsound>

Function:

Plays a soundtrack in the document background

Attributes:

LOOP
SRC

End tag:

None

Contains:

Nothing

Used in:

body_content

The src attribute

The src attribute is required for the <bgsound> tag. Its value references the URL for the related sound file. For example, when the Internet Explorer user first downloads an HTML document containing the tag:

<bgsound src="audio/welcome.wav">

they will hear the welcome.wav audio file--perhaps an inviting message--play once through their computer's sound system.

Currently, Internet Explorer can handle three different sound format files: wav, the native format for PCs; au, the native format for most Unix workstations; and MIDI, a universal music-encoding scheme (see also Table 5-1 ).

 

Common Multimedia Formats and Respective Filename Extensions

Format

Type

Extension

Platform of Origin

GIF

Image

gif

Any

JPEG

Image

jpg, jpeg, jpe

Any

XBM

Image

xbm

Unix

TIFF

Image

tif, tiff

Any

PICT

Image

pic, pict

Any

Rasterfile

Image

ras

Sun

MPEG

Movie

mpg, mpeg

Any

AVI

Movie

avi

Microsoft

QuickTime

Movie

qt, mov

Apple

AU

Audio

au, snd

Sun

WAV

Audio

wav

Microsoft

AIFF

Audio

aif, aiff

Apple

MIDI

Audio

midi, mid

Any

PostScript

Document

ps, eps, ai

Any

Acrobat

Document

pdf

Any

The loop attribute

Like Internet inline movies, the loop attribute for the browser's <bgsound> tag lets you replay a background soundtrack for a certain number of times (or over and over again forever), at least until the user moves on to another page or quits the browser.

The value of the loop attribute is the integer number of times to replay the audio file, or infinite, which makes the soundtrack repeat endlessly.

For example:

<bgsound src="audio/tadum.wav" loop=10>

repeats the ta-dum soundtrack ten times, whereas:

<bgsound src="audio/noise.wav" loop=infinite>

continuously plays the noise soundtrack.

Alternative Audio Support

There are other ways to include audio in your documents, using more general mechanisms that support other embedded media as well. The most common alternative to the <bgsound> tag is the <embed> tag, originally implemented by Netscape and supplanted by the <object> HTML standard 4.0 tag. Take a look in Chapter 13 for details.

Animated Text

In what appears to be an effort to woo advertisers, Internet Explorer has added a form of animated text to HTML. The animation is simple--text scrolling horizontally across the display--but effective for moving banners and other elements that readily and easily animate an otherwise static document. On the other hand, like the <blink> tag, animated text can easily become intrusive and abusive for the reader. Use with caution, please, if at all.

The <marquee> Tag

The <marquee> tag defines the text that scrolls across the Internet Explorer user's display.

<marquee>

Function:

Create a scrolling text marquee

Attributes:

ALIGN
BEHAVIOR
BGCOLOR
DIRECTION
HEIGHT
HSPACE
LOOP
SCROLLAMOUNT
SCROLLDELAY
VSPACE
WIDTH

End tag:

</marquee>; never omitted

Contains:

plain_text

Used in:

body_content

The <marquee> tag is for Internet Explorer only, and it is an extension to the HTML 4.0 standard. The text between the <marquee> tag and its required </marquee> end tag scrolls horizontally across the display. The various tag attributes control the size of the display area, its appearance, its alignment with the surrounding text, and the scrolling speed.

The <marquee> tag and attributes are ignored by other browsers, but its contents are not. They are displayed as static text, sans any alignment or special treatments afforded by the <marquee> tag attributes.

The align attribute

Internet Explorer places <marquee> text into the surrounding body content just as if it were an embedded image. As a result, you can align the marquee within the surrounding text.

The align attribute accepts a value of top, middle, or bottom, meaning that the specified point of the marquee will be aligned with the corresponding point in the surrounding text. Thus:

<marquee align=top>

aligns the top of the marquee area with the top of the surrounding text. Also see the height and width, hspace, and vspace attributes (later in this chapter), which control the dimensions of the marquee.

The behavior, direction, and loop attributes

Together, these three attributes control the style, direction, and duration of the scrolling in your marquee.

The behavior attribute accepts three values:

scroll (default)

The value of scroll causes the marquee to act like the grand marquee in Times Square: the marquee area is empty initially; the text then scrolls in from one side (controlled by the direction attribute), continues across until it reaches the other side of the marquee, and then scrolls off until the marquee is once again empty.

slide

This value causes the marquee to start empty. Text then scrolls in from one side (controlled by the direction attribute), stops when it reaches the other side, and remains onscreen.

alternate

Specifying alternate as the value for the behavior attribute causes the marquee to start with the text fully visible at one end of the marquee area. The text then scrolls until it reaches the other end, whereupon it reverses direction and scrolls back to its starting point.

If you do not specify a marquee behavior, the default behavior is scroll.

The direction attribute sets the direction for marquee text scrolling. Acceptable values are either left (the default) or right. Note that the starting end for the scrolling is opposite to the direction: left means that the text starts at the right of the marquee and scrolls to the left. Remember also that rightward-scrolling text is counter-intuitive to anyone who reads left to right.

The loop attribute determines how many times the marquee text scrolls. If an integer value is provided, the scrolling action is repeated that many times. If the value is infinite , the scrolling repeats until the user moves on to another document within the browser.

Putting some of these attributes together:

<marquee align=center loop=infinite>
  Kumquats aren't filling
  ..........      Taste great, too! 
</marquee>

The example message starts at the right side of the display window (default), scrolls leftward all the way across and off the Internet Explorer display, and then starts over again until the user moves on to another page. Notice the intervening periods and spaces for the "trailer"; you can't append one marquee to another.

Also, the slide -style of scrolling looks jerky when repeated and should only be scrolled once. Other scrolling behaviors work well with repeated scrolling.

The bgcolor attribute

The bgcolor attribute lets you change the background color of the marquee area. It accepts either an RGB color value or one of the standard color names. See Appendix F for a full discussion of both color-specification methods.

To create a marquee area whose color is yellow, you would write:

<marquee bgcolor=yellow>

The height and width attributes

The height and width attributes determine the size of the marquee area. If not specified, the marquee area extends all the way across the Internet Explorer display and will be just high enough to enclose the marquee text.

Both attributes accept either a numeric value, indicating an absolute size in pixels, or a percentage, indicating the size as a percentage of the browser window height and width.

For example, to create a marquee that is 50 pixels tall and occupies one-third of the display window width, use:

<marquee height=50 width="33%">

While it is generally a good idea to ensure the height attribute is large enough to contain the enclosed text, it is not uncommon to specify a width that is smaller than the enclosed text. In this case, the text scrolls the smaller marquee area, resulting in a kind of "viewport" marquee familiar to most people.

The hspace and vspace attributes

The hspace and vspace attributes let you create some space between the marquee and the surrounding text. This usually makes the marquee stand out from the text around it.

Both attributes require an integer value specifying the space needed in pixels. The hspace attribute creates space to the left and right of the marquee; the vspace attribute creates space above and below the marquee. To create 10 pixels of space all the way around your marquee, for example, use:

<marquee vspace=10 hspace=10>

The scrollamount and scrolldelay attributes

These attributes control the speed and smoothness of the scrolling marquee.

The scrollamount attribute value is the number of pixels needed to move text each successive movement during the scrolling process. Lower values mean smoother, but slower scrolling; higher numbers create faster, but jerkier text motion.

The scrolldelay attribute lets you set the number of milliseconds to wait between successive movements during the scrolling process. The smaller this value, the faster the scrolling.

You can use a low scrolldelay to mitigate the slowness of a small, smooth scrollamount. For example:

<marquee scrollamount=1 scrolldelay=1>

scrolls the text one pixel for each movement, but does so as fast as possible. In this case, the scrolling speed is limited by the capabilities of the browser's computer.

Other Multimedia Content

The Web is completely open-minded about the types of content that can be exchanged by servers and browsers. In this section, we look at a different way to reference images, along with audio, video, and other document formats.

Embedded Versus Referenced Content

Images currently enjoy a special status among the various media that can be included within an HTML document and displayed inline with other content by all but a few browsers. Sometimes, however, as we discussed earlier in this chapter, you may also reference images externally, particularly large ones in which details are important, but not immediately necessary to the document content. Other multimedia elements, including digital audio and video, can be referenced as separate documents external to the current one.

You normally use the anchor tag (<a> ) to link external multimedia elements to the current document. Just like other link elements selected by the user, the browser downloads the multimedia object and presents it to the user, possibly with the assistance of an external application or plug-in. Referenced content is always a two-step process: present the document that links to the desired multimedia object, then present the object if the user selects the link.

In the case of images, you can choose how to present images to the user: inline and immediately available via the <img> tag, or referenced and subsequently available via the <a> tag. If your images are small and critical to the current document, you should provide them inline. If they are large or are only a secondary element of the current document, make them available as referenced content via the <a> tag.

If you choose to provide images via the <a> tag, it is sometimes a courtesy to your readers to indicate the size of the referenced image in the referencing document and perhaps provide a thumbnail sketch. Users can then determine whether it is worth their time and expense to retrieve it.

Referencing Audio, Video, and Images

You reference any external document, regardless of type or format, in an HTML document via a conventional anchor (<a> ) link:

The <a href="sounds/anthem.au">Kumquat Grower's Anthem</a> is a rousing tribute to the thousands of 'quat growers around the world.

Just like any referenced document, the server delivers the desired multimedia object to the browser when the user selects the link. If the browser finds the document is not HTML, but some other format, it automatically invokes an appropriate rendering tool to display or otherwise convey the contents of the object to the user.

You can configure your browser with special helper applications that handle different document formats in different ways. Audio files, for example, might be passed to an audio-processing tool, while video files are given to a video-playing tool. If a browser has not been configured to handle a particular document format, the browser will inform you and offer to simply save the document to disk. You can later use an appropriate viewing tool to examine the document.

Browsers identify and specially handle multimedia files from one of two different hints: either from the file's Multipurpose Internet Mail Extension (MIME) type provided by the server or from a special suffix in the file's name. The browser prefers MIME because of its richer description of the file and its contents, but will infer the file's contents (type and format) of the object by the file suffix; .gif or .jpg, for GIF and JPEG encoded images, for example, or .au for a special sound file.

Since not all browsers look for a MIME type, nor will they all be correctly configured with helper applications by their users, you should always use the correct file suffix in the names of multimedia objects. See Table 5-1 for examples.

Appropriate Linking Styles

Creating effective links to external multimedia documents is critical. The user needs some indication of what the object is and perhaps the kind of application the linked object needs to execute. Moreover, most multimedia objects are quite large, so common courtesy tells us to provide users with some indication of the time and expense involved in downloading it.

In lieu of, or in addition to, the anchor and surrounding text, a small thumbnail of large images or a familiar icon that indicates the referenced object's format may be useful.

Embedding Other Document Types

The Web can deliver nearly any type of electronic document, not just graphics, sound, and video files. To display them, however, the client browser needs a helper application installed and referenced. Recent browsers also support plug-in accessory software and, as described in Chapter 13, may extend the browser for some special function, including inline display of multimedia objects.

For example, consider a company whose extensive product documentation was prepared and stored in some popular layout application like FrameMaker, Quark XPress, or PageMaker. The Web offers an excellent way for distributing that documentation over a worldwide network, but converting to HTML would be too costly at this time.

The solution is to prepare a few HTML documents that catalog and link the alternative files and invoke the appropriate display applet. Or, make sure that the users' browsers have the plug-in software or are configured to invoke the appropriate helper application--FrameMaker, for example, if the document is in FrameMaker format. Then, if a link to a FrameMaker document is chosen, the tool is started and accordingly displays the document.

 


1. A pixel is one of the many tiny dots that make up the display on your computer. While display sizes vary, a good rule of thumb is that one pixel equals one point on a common 75 dot-per-inch display monitor. A point is a unit of measure used in printing and is roughly equal to 1 / 72 of an inch (there are 72.27 points in an inch, to be exact). Typical typefaces used by various browsers are usually 12 points tall, yielding six lines of text per inch.

2. We cannot resist the temptation to point out that choosy authors choose GIF.

3. Songline Studios has published an entire book dedicated to GIF animation: GIF Animation Studio, by Richard Koman.

4. Most of the popular graphical browsers normally insert an image so that its base aligns with the baseline of the text--the same alignment as that specified by the attribute value of bottom. Nonetheless, HTML document designers should assume that alignment varies between browsers and always include the desired type of image alignment.

5. This is one way to create colored horizontal rules in Netscape 3 or earlier versions, which don't support the color attribute of the <hr> tag.


oreilly.com Home | O'Reilly Bookstores | How to Order | O'Reilly Contacts
International | About O'Reilly | Affiliated Companies | Privacy Policy

© 2001, O'Reilly & Associates, Inc.