Lesson 8

Working with Colors, Images, and Multimedia

What You’ll Learn in This Lesson:

  • Image How to choose colors for your website that work on the web

  • Image How to use CSS to set background, text, and border colors

  • Image How to select a graphics software package to use

  • Image How to prepare photographs for use online

  • Image How to create banners and buttons

  • Image How to reduce the number of colors in an image

  • Image How to create transparent images

  • Image How to prepare an image for a tiled background

  • Image How to create animated web graphics

  • Image How to place an image on a web page

  • Image How to describe images with text

  • Image How to specify image height and width

  • Image How to align images

  • Image How to use background images

  • Image How to use image maps

  • Image How to link to or embed multimedia files

  • Image How to use HTML5 audio and video elements

This lesson covers a lot of topics, but have no fear, for each of these tasks is short and sweet, and this lesson will help you move your web development experience from the white background/black text examples so far in this series to more interesting (or at least colorful) examples. But that’s not to say that dark text on a light background is bad; in fact, it’s the most common color combination you’ll find online.

Paying attention to color schemes and producing a visually appealing website is important, but you don’t have to be an artist by trade to implement high-impact color schemes in your website or to put a few appealing flourishes on what would otherwise be a drab, square world. You don’t need to spend hundreds or thousands of dollars on software packages, either, just to manipulate digital photographs or other source graphics you might want to use. The topics in this lesson should help you understand the very basics of color theory and how to modify colors using CSS, as well as how to create images you can use in your website.

Note

Although the sample figures in this lesson use a popular and free graphics program for Windows, Mac, and Linux users (GNU Image Manipulation Program [GIMP]), you can apply the knowledge you learn in this lesson to any major Windows or Mac graphics application—although the menus and options will look different, of course.

After you learn to create the graphics themselves, you’ll be ready to include them in your website. Beyond just the basics of using the HTML <img> tag to include images for display in a web browser, you’ll learn how to provide descriptions of these images (and why). You’ll also learn about image placement, including how to use images as backgrounds for different elements. You’ll learn how to use image maps, which enable you to use a single image as a link to multiple locations.

Finally, you’ll learn a little bit about working with multimedia. The term multimedia encompasses everything we see and hear on a web page: audio, video, and animation, as well as static images and text. Although you won’t learn how to create any particular audio or video, you will learn how to include such files in your site, through either linking or embedding the content.

Best Practices for Choosing Colors

We can’t tell you exactly which colors to use in your website, but we can help you understand certain considerations when selecting colors on your own. The colors you use can greatly influence your visitors; for example, if you are running an e-commerce site, you want to use colors that entice your users to view your catalog and eventually purchase something. If you are creating a text-heavy site, you want to make sure the color scheme helps create easy-to-read text. Overall, you want to make sure you use colors judiciously and with respect.

You might wonder how respect enters into the mix when talking about colors. Remember that the World Wide Web is an international community and that people’s interpretations differ. For instance, pink is very popular in Japan but very unpopular in Eastern European countries. Similarly, green is the color of money in the United States, but the vast majority of other countries have multicolored paper bills—“the color of money” thus isn’t a single color at all, so the metaphor would be of no value to international visitors.

Besides using culturally sensitive colors, other best practices include the following:

  • Image Use a natural palette of colors—This doesn’t mean you should use earth tones; rather, you should use colors that you would naturally see on a casual stroll around town and avoid ultra-bright colors that can cause eye strain.

  • Image Use accessible color combinations—Color blindness is not uncommon, and you should avoid using color as the only differentiator for important information. For example, if you need to display a warning, you can change the text or background color, but you should also add an icon or other aid to indicate the problem. For accessibility, you might consider using the Toptal Colorblind Web Page Filter tool at www.toptal.com/designers/colorfilter to see how your site looks to a person with colorblindness.

  • Image Use colors with good contrast, especially for blocks of text—The reason that black text on a white background is so popular is because it has good contrast and so is easy to read. Avoid using background/foreground color combinations that have too little contrast. You can test the contrast of two colors at https://webaim.org/resources/contrastchecker/.

  • Image Use a small color palette—You don’t need to use 15 colors to achieve your goals. In fact, if your page includes text and images in 15 colors, you might reevaluate the message you’re attempting to send. Focus on 3 or 4 main colors, with 1 or 2 complementary colors at most.

  • Image Consider your demographics—You likely can’t control your demographics, so you have to find a middle ground that accommodates everyone. The colors younger people enjoy are not necessarily the same ones older people appreciate, just as there are color biases between men and women and between people from different geographic regions and cultures.

You might now be thinking that your color options are limited. Not so. You simply need to think about the decisions you’re making before you make them. A search for “color theory” in the search engine of your choice should give you more food for thought, as will the use of a color wheel.

A color wheel is a chart that shows the organization of colors in a circular manner. Its method of display is an attempt to help you visualize the relationships among primary, secondary, and complementary colors. Color schemes are developed from working with the color wheel; understanding color schemes can help you determine the color palette to use consistently throughout your website. For example, knowing something about color relationships will hopefully enable you to avoid using orange text on a light blue background, or bright blue text on a brown background.

Some common color schemes in web design are given here:

  • Image Analogous—Using colors that are adjacent to each other on the color wheel, such as yellow and green. One color is the dominant color, and its analogous friend enriches the display.

  • Image Complementary—Using colors that are opposite each other on the color wheel, such as a warm color (red) and a cool color (green).

  • Image Monochromatic—Using colors that are all the same primary hue. The secondary colors are created by adding white and black to the primary color.

  • Image Triadic—Using three colors that are equally spaced around the color wheel. The triadic scheme provides balance while still allowing rich color use.

Entire books and courses are devoted to understanding color theory, so continuing the discussion in this lesson would indeed be a tangent. However, if you intend to work in web design and development, you will be served well with a solid understanding of the basics of color theory. Spend some time reading about it; an online search will provide a wealth of information.

In addition, spend some hands-on time with the color wheel. The color scheme designer Paletton, at http://paletton.com, enables you to start with a base color and produce monochromatic, complementary, triadic, tetradic, analogic, and accented analogic color schemes.

Understanding Web Colors

Specifying a background color other than white for a web page is easier than you probably realize. For example, to specify blue as the background color for a page, put style="background-color:blue;" inside the <body> tag or in the style sheet rule for the body element. Of course, you can use many colors other than blue. In fact, the W3C standards list 16 colors: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow.

Note

The CSS color gray has the U.S. spelling in the standards document. But most web browsers also support grey as an alternate spelling. However, the CSS style properties color and background-color must be spelled with the U.S. spelling.

Obviously, many more than just those 16 colors are displayed on the Web. In fact, you can use 140 color names with the assurance that all browsers will display these colors similarly. Here’s a partial list of the 140 descriptive color names: azure, bisque, cornflowerblue, darksalmon, firebrick, honeydew, lemonchiffon, papayawhip, peachpuff, saddlebrown, thistle, tomato, wheat, and whitesmoke.

Note

For a complete list of the 140 descriptive color names, as well as their hexadecimal codes and an example of the color as displayed by your browser, visit www.w3.org/TR/SVG/types.html#ColorKeywords.

But names are subjective. For instance, if you look at the color chart of 140 cross-browser color names, you’ll see that you can’t distinguish between fuchsia and magenta. The associated RGB color values for those two color, fuchsia and magenta, are also exactly the same: rgb(255, 0, 255). You’ll learn about RGB color values in the next section, but for now, know that if you want to be standards compliant and use more than the 16 color names the W3C standards dictate, you should use RGB or hexadecimal color values.

Note

Color names are not case sensitive. So Black, black, and BLACK are all black, although most web designers stick with lowercase or mixed case (if they use color names at all; most designers use hexadecimal notation for a more nuanced approach to color use).

Hexadecimal color codes make possible 16 million colors, and most modern computer displays can display all of them. However, be aware that not all computer monitors display colors in the same hues. What might appear as a beautiful light blue background color on your monitor might be more of a purple hue on another user’s monitor. Neutral, earth-tone colors (such as medium gray, tan, and ivory) can produce even more unpredictable results on many computer monitors. These colors might even seem to change color on a single monitor, depending on lighting conditions in the room or the time of day.

In addition to changing the background of your pages to a color other than white, you can change the color of text links, including various properties of links (such as the color for when a user hovers over a link versus when the user clicks a link—as you learned in previous lessons). You can also set the background color of container elements (such as paragraphs, sections, block quotes, and table cells), and you can use colors to specify the borders around those elements. You’ll see some examples of colors and container elements later in this lesson.

There are plenty of very bad websites, some created by earnest people with no trace of irony whatsoever. However, the World’s Worst Website, in Figure 8.1, was purposefully created to show some of the more egregious sins of website design, especially in terms of the use of colors. A screenshot does not do it justice, though (especially in the printed version of this book, which is in black and white), so visit and experience the site for yourself, at www.angelfire.com/super/badwebs/main.htm. For the full effect, make sure to have your sound turned on.

A screenshot displays the "Worlds Worst web" window that consists of links and website designs in color.
Figure 8.1 A partial screenshot of the World’s Worst Website.

If you search for “bad website examples” in your search engine, you will find many sites that collect examples of bad design and explain just why such a site should be in a Hall of Shame rather than a Hall of Fame. Many sites are considered bad because of their visual displays, and the display begins with color selection. Therefore, understanding colors, including the nuances of their specification and use, is a crucial step in creating a good website.

Using Hexadecimal Values for Colors

To remain standards compliant, as well as to retain precise control over the colors in your website, you can reference colors by their hexadecimal values. The hexadecimal value of a color is an indication of how much red, green, and blue light should be mixed into each color. It works a little bit like Play-Doh: Just mix in the amounts of red, blue, and green you want in order to get the appropriate color.

The hexadecimal color format is #rrggbb, in which rr, gg, and bb are two-digit hexadecimal values for the red (rr), green (gg), and blue (bb) components of the color. If you’re not familiar with hexadecimal numbers, don’t sweat it. Just remember that ff is the maximum, and 00 is the minimum. Use one of the following codes for each component:

  • Image ff means full brightness.

  • Image cc means 80% brightness.

  • Image 99 means 60% brightness.

  • Image 66 means 40% brightness.

  • Image 33 means 20% brightness.

  • Image 00 means none of this color component.

For example, bright red is #ff0000, dark green is #003300, bluish-purple is #660099, and medium gray is #999999. To make a page with a red background and dark green text, you could use the following HTML code within inline styles:

<body style="background-color:#ff0000; color:#003300;">

Although only 6 examples of two-digit hexadecimal values are shown here, there are actually 256 combinations of two-digit hexadecimal values: 09 and af, paired up. For example, f0 is a possible hex value (decimal value 240), 62 is a possible hex value (decimal value 98), and so on.

As previously discussed, the rr, gg, and bb in the #rrggbb hexadecimal color code format stand for the red, green, and blue components of the color. Each of those components has a decimal value ranging from 0 (no color) to 255 (full color).

So white (or #ffffff) translates to a red value of 255, a green value of 255, and a blue value of 255. Similarly, black (#000000) translates to a red value of 0, a green value of 0, and a blue value of 0. True red is #ff0000 (all red, no green, and no blue), true green is #00ff00 (no red, all green, no blue), and true blue is #0000ff (no red, no green, and all blue). All other hexadecimal notations translate to some variation of the 255 possible values for each of the three colors. The cross-browser-compatible color name cornflowerblue is associated with the hexadecimal notation #6495ed—a red value of 100, a green value of 149, and a blue value of 237 (almost all of the available blue values).

When picking colors, either through a graphics program or by finding something online that you like, you might see the color notation in hexadecimal or decimal. If you type “hexadecimal color converter” into your search engine, you will find numerous options to help you convert color values into something you can use in your style sheets.

Using RGB and RGBa Values for Colors

Hexadecimal codes define the red, green, and blue percentages of each color for millions of colors. But you can also define those colors with RGB values. The RGB format is rgb(red, green, blue), where red, green, and blue are values of 0 to 255—just like hexadecimal, but written in base-10 numbers (decimal) rather than base-16 (hexadecimal). You simply need to remember that 255 is the maximum, and 0 is the minimum.

Use the following values in your RGB colors:

  • Image 255 means full brightness.

  • Image 204 means 80% brightness.

  • Image 153 means 60% brightness.

  • Image 102 means 40% brightness.

  • Image 51 means 20% brightness.

  • Image 0 means none of this color component.

To make a page with a red background and dark green text using RGB, you could use the following CSS:

background-color:rgb(255,0,0); color:rgb(0,51,0);

Every hexadecimal color code has a corresponding RGB code. So white (or #ffffff) is the same as rgb(255,255,255). Black (#000000) is rgb(0,0,0). True red is rgb(255,255,255), true green is rgb(0,255,0), and true blue is rgb(0,0,255). All other hexadecimal notations translate to some variation of the 255 possible values for each of the three colors. The cross-browser-compatible color name cornflowerblue is associated with the hexadecimal notation #6495ed and the RGB notation rgb(100,149,237). There are lots of color conversion apps online.

Designers often use RGB codes because a lot of graphics programs are set up to use RGB. But the better reason to use RGB is RGBa—RGB with alpha transparency. RGBa allows you to set the opaqueness or transparency of a color. The more transparent a color is, the more of the background color will show through.

To define the alpha transparency, you write your RGB color with one extra value: rgba(red, green, blue, transparency). The transparency value is a number between 0 and 1, representing the transparency percentage. 0 is fully transparent, meaning the background is all you see, 1 is fully opaque meaning the background is completely covered, and 0.5 is 50% transparent.

To make a page with faded cornflowerblue text on a white background, you could use this CSS:

body { color: rgba(100,149,237,0.5); }

You could then change the transparency to 1 for bold text, to make it stand out more, with this CSS:

strong { color: rgba(100,149,237,1); font-weight: normal; }

Remember when using RGBa that the color of the foreground depends on the color of the background. While rgba(100,149,237,0.5) is a pale blue on a white background, it is going to look darker on a black background.

Using CSS to Set Background, Text, and Border Colors

When using CSS, it’s most common to use color values in three instances: when specifying the background color, the text color, or the border color of elements. In Lesson 7, “Using External and Internal Links,” you learned about using colors for various link states, and in this lesson, we focus on basic element display.

Figure 8.2 shows an example of color usage that could very easily go into a web design Hall of Shame. We can’t imagine ever using these combinations of colors and styles in a serious website, but it serves here as an example of how color style could be applied to various elements. The image printed here will likely not do justice to the horrific colors used (especially if you’re reading a printed copy of this book, which is in black and white) so be sure to open the sample file or type up the code in Listing 8.1 and load it in your browser.

A screenshot shows a web browser that displays the texts with different background, text, and border colors.
Figure 8.2 You can set background, text, and border colors by using CSS.

Listing 8.1 shows the HTML and CSS styles used to produce Figure 8.2.

Listing 8.1 Using Styles to Produce Background, Text, and Border Colors

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Background, Text, and Border Colors</title>
    <style>
    #uglyparagraph {
       background-color: #cccccc;
       color: #ff0000;
       border:1px solid #000000;
    }
    .orange {
       color: #ffa500
    }
    #uglydiv {
       width: 300px;
       height: 75px;
       margin-bottom: 12px;
       background-color: #000000;
       border: 2px dashed #ff0000;
       color: #ffffff;
    }
    table {
       border: 1px solid #000;
       border-spacing: 2px;
       border-style: outset;
       border-collapse: collapse;
    }
    .greencell {
       background-color: #00ff00;
    }
    .redcell {
       background-color: #ff0000;
    }
    .bluecell {
       background-color: #0000ff;
    }
    .yellowcell {
       background-color: #ffff00;
    }
    #uglybq {
       background-color: #0000ff;
       border:4px dotted #ffff00;
       color:#ffffff;
    }
    </style>
  </head>
  <body>
    <h1>Background, Text, and Border Colors</h1>
    <p id="uglyparagraph">Grey paragraph, black border, red text
    with an <span class="orange">orange span</span>.</p>
    <div
id="uglydiv">Black div, red border, white text. </div>
    <table>
      <tr>
        <td class="greencell">Green Table Cell</td>
        <td class="redcell">Red Table Cell</td>
      </tr>
      <tr>
        <td class="bluecell">Blue Table Cell</td>
        <td class="yellowcell">Yellow Table Cell</td>
      </tr>
    </table>
    <blockquote id="uglybq">
      Blue blockquote, yellow border, white text.
    </blockquote>
  </body>
</html>

Looking at the styles in Listing 8.1, you should be able to figure out almost everything except some of the border styles. In CSS you can’t designate a border as a color without also having a width and type. In the first example in Listing 8.1, for uglyparagraph, the border width is 1px, and the border type is solid. In the example for uglydiv, the border width is 2px, and the border type is dashed. In the uglybq example, the border width is 4px, and the border type is dotted.

When picking colors for your website, remember that a little goes a long way. If you really like a bright and spectacular color, use it as an accent color, not throughout the primary design elements. In addition, remember that light backgrounds with dark text are much easier to read than dark backgrounds with light text.

Choosing Graphics Software

You can use almost any graphics program to create and edit images for your website, from the simple painting or drawing program that typically comes free with your computer’s operating system, to an expensive professional program such as Adobe Photoshop. Similarly, if you have a digital camera or scanner attached to your computer, it probably came with some graphics software capable of creating images suitable for online use. Several free image editors also are available for download—or even online as web applications—that deal just with the manipulation of photographic elements.

Note

Without a doubt, Adobe Photoshop is the cream of the crop when it comes to image-editing programs. However, it is expensive and quite complex and so may not be a great choice for someone who doesn’t have experience working with computer graphics. For more information on Adobe’s products, visit the Adobe website, at www.adobe.com. If you are in the market for one of the company’s products, you can download a free evaluation version from the site.

If you already have software you think might be good for creating web graphics, try using it to do everything described in these next sections. If your software can’t handle some of the tasks covered here, it probably isn’t a good tool for web graphics. In that case, download and install GIMP from www.gimp.org. This fully functional graphics program is completely free and can definitely perform the actions shown in this lesson.

Using Images Found Elsewhere

One of the best ways to save time creating graphics and media files for web pages is, of course, to avoid creating them altogether. Grabbing a graphic from any web page is as simple as right-clicking it (or Option+clicking with an Apple mouse) and selecting Save Image As or Save Picture As (depending on the browser). Extracting a background image from a page is just as easy: Right-click it and select Save Background As.

However, you should never use images without the explicit permission of the owner, either by asking or by looking for a Creative Commons license. Using images without explicit permission is a copyright violation (and is also distasteful). To learn more about copyrights, we recommend the Copyright Crash Course online tutorial from the University of Texas, at  http://guides.lib.utexas.edu/copyright.

You might also want to consider using royalty-free clip art, which doesn’t require you to get copyright permission. One good source of copyright-free photos and images is Pixabay (https://pixabay.com). These images are released under Creative Commons CC0, which makes them free to use without permission or attribution, even for commercial purposes. Clipart.com is a popular clip art destination; for a small fee this site gives you access to thousands of stock images.

If GIMP doesn’t suit you, consider downloading the evaluation version of CorelDRAW for Windows or Macintosh (www.coreldraw.com) or Acorn for Macintosh (https://flyingmeat.com/acorn/). For photo manipulation only, there are many free options, all with helpful features. Pixlr (https://pixlr.com) is a good option. It is suited for editing images rather than creating them from scratch. These types of programs won’t necessarily help you design a banner or button image for your site; however, they can help you work with some supplementary images, and they are powerful enough that they’re worth checking out.

The Least You Need to Know About Graphics

Two forces are always at odds when you post graphics and multimedia on the Internet. The users’ eyes and ears want all your content to be as detailed and accurate as possible, and they also want information to be displayed immediately. Intricate, colorful graphics mean big file sizes, which increase the transfer time—even over a fast connection. How do you maximize the quality of your presentation while minimizing file size? To make these choices, you need to understand how color and resolution work together to create a subjective sense of quality.

The resolution of an image is the number of individual dots, or pixels, that make up an image (typically 72 dots per inch, or 72dpi). Large, high-resolution images generally take longer to transfer and display than small, low-resolution images. Image dimensions are usually specified as the width times the height of the image, expressed in pixels; a 300 × 200 image, for example, is 300 pixels wide and 200 pixels high.

Note

Several types of image resolution are used, including pixel, spatial, spectral, temporal, and radiometric. You could spend hours just learning about each type—and if you were taking a graphics design class, you might do just that. For now, however, all you need to remember is that large images take longer to download and also use a lot of space in your display. Display size and storage or transfer size are factors to take into consideration when you are designing a website.

You might be surprised to find that resolution isn’t the most significant factor in determining an image file’s storage size (and transfer time). This is because images used on web pages are always stored and transferred in compressed form. Image compression is the mathematical manipulation that images are put through to squeeze out repetitive patterns. The mathematics of image compression are complex, but the basic idea is that repeating patterns or large areas of the same color can be squeezed out when the image is stored on a disk. This makes the image file much smaller and allows it to be transferred faster over the Internet. The web browser then restores the original appearance of the image when the image is displayed.

In the sections that follow, you’ll learn how to create graphics with big visual impact but small file sizes. The techniques you use to accomplish this depend on the contents and purpose of each image. There are as many uses for web graphics as there are web pages, but four types of graphics are by far the most common:

  • Image Photos of people, products, and places

  • Image Graphical banners and logos

  • Image Buttons or icons to indicate actions and provide links

  • Image Background textures for container elements

Preparing Photographic Images

To put photos on your web pages, you need to convert your print-based photos to digital images or create photos digitally by using a digital camera, such as the camera in your smartphone. In the case of some older models of hardware, you might need to use the custom software that came with your device to transfer images to your hard drive, but in most cases, you should be able to connect your device and then drag and drop files to your hard drive. If you are using a scanner to create digital versions of your print photos, you can control just about any scanner directly from the graphics program of your choice; see your software documentation for details.

Note

If you don’t have a scanner or digital camera, note that almost all film developers offer the service of transferring photos from 35mm film to a CD-ROM or DVD-ROM for a modest fee. You can then copy the files to your hard drive and use your graphics program to open and modify the image files.

After you transfer the digital image files to your computer, you can use your graphics program to crop, resize, color-correct, and compress to get them ready for use in your website.

Cropping an Image

Because you want web page graphics to be as compact as possible, you usually need to crop your digital photos. When you crop a photo, you select the area you want to display and crop away the rest.

Even after your image has been cropped, it might be larger than it needs to be for a web page. For most responsive designs, your images don’t need to be more than 2000 pixels wide. This would allow the image to expand up to 2000px on large screens without losing quality. If you never plan on using the image all by itself on a page, you can crop the image smaller, but the larger the starting image is, the more screens it will support.

Note

Your graphics software will likely have an omnipresent size display somewhere in the image window itself. In GIMP, you can see the current image size in the window title bar. Other programs might show it in the lower-right corner or the lower-left corner. You might also see the magnification ratio in the window, and you might be able to change it by zooming in or out.

The key to good cropping is to remove unwanted details from the image. One way to do this is with the rule of thirds. Positioning the interesting elements at the top, right, bottom, or left third of the image makes the whole thing more visually interesting. Other cropping rules you can apply include the golden ratio, golden spiral, triangle, and diagonal crops.

Resizing an Image

The exact tool necessary to change an image’s size depends on the program you are using. In GIMP, go to the Image menu and click Scale Image to open the Scale Image dialog box (see Figure 8.5).

A screenshot shows the Scale Image dialog box.
Figure 8.5 Use the Scale Image dialog box to change the size of an image.

You’ll almost always want to resize using the existing aspect ratio, meaning that when you enter the width you’d like the image to be, the height is calculated automatically (and vice versa) to keep the image from squishing out of shape. In GIMP, the aspect ratio is locked by default, as indicated by the chain link displayed next to the Width and Height options shown in Figure 8.5. Clicking once on the chain unlocks it, enabling you to specify pixel widths and heights of your own choosing—squished or not.

Note

As with many other features in GIMP, the Scale Image dialog box appears in front of the window containing the image being resized. This placement enables you to make changes in the dialog box, apply them, and see the results immediately.

In most, if not all, graphics programs, you can also resize an image based on percentages instead of by providing specific pixel dimensions. For example, if an image starts out as 1815 × 1721 and you don’t want to do the math to determine the values necessary to show it as half that size, you can simply select Percent (in this instance, from the drop-down next to the pixel display in Figure 8.5) and change the default setting from 100 to 50. The image then becomes 908 pixels wide by 861 high—and you don’t have to do any math to make it so.

Caution

You should never resize an image to be larger than what you started with. While most image editors will allow you to enlarge images, they typically don’t do a good job of it. This is because enlarging an image beyond the starting image requires that the editor make guesses about what the additional pixels should be. This can result in ugly, blurry images. Instead, you should start with images that are much larger than you think you would ever need and then resize and crop them down to fit your web designs.

Deciding the right size for a web page image can be challenging. You need to always consider download speeds and the size of the device or screen viewing the page, plus the amount of space available in the design for the image. A good rule of thumb is to create images that are slightly larger than the largest width at which they might display. While people do have large 4K monitors, 1920 × 1080 is the most common large size monitor. So, resizing your images to be no more than 2000 pixels wide will ensure that they look good even on large monitors while keeping the file size small. Later in this lesson you will learn how to use the same image at several sizes for responsive web design.

Note

It can be tempting to crop and resize your images down as small as possible, and for best speed you should. But always keep a copy of the original, full-sized file offline or in a backup location. This way, if two years from now you want to resize your website to be larger, you’re not limited by the 640 × 480 images you created for the old design.

Tweaking Image Colors

If you are editing photographic images instead of creating your own graphics, you might need to use some color-correction tools to get photos just right. Like many other image-editing programs, GIMP offers several options for adjusting an image’s brightness, contrast, and color balance, as well as a filter to reduce the dreaded red-eye. To remove red-eye using GIMP, go to Filters, click Enhance, and then click Red Eye Removal.

Most of these options are pretty intuitive. If you want an image to be brighter, adjust the brightness. If you want more red in your image, adjust the color balance. In GIMP, the Colors menu gives you access to numerous tools. As with the Scale Image dialog box described in the preceding section, each tool displays a dialog box in the foreground of your workspace. As you adjust the colors, the image reflects those changes. This preview function is a feature included in most image-editing software.

Figure 8.6 shows the Adjust Hue/Lightness/Saturation tool, one of the many tools provided on the Colors menu. As shown in the figure, you can achieve many color-related changes by using various sliders in dialog boxes to adjust the values you are working with. The Preview feature enables you to see what you are doing as you are doing it. The Reset Color button returns the image to its original state without applying any changes.

A screenshot displays the Adjust Hue/Lightness/saturation tool.
Figure 8.6 The Adjust Hue/Lightness/Saturation tool is one of many slider-based color-modification tools available in GIMP. (Credit: Scott Prokop/Shutterstock)

Because of the numerous tools available to you, and the preview function available with each tool, a little playful experimentation is the best way to find out what each tool does.

Controlling JPEG Compression

Photographic images on the web work best when saved in the JPEG file format rather than GIF; JPEG enables you to retain the number of colors in the file while still keeping the overall file size to a manageable level. When you’re finished adjusting the size and appearance of a photo, select File, Export, and choose JPEG as the file type. Your graphics program will likely provide you with another dialog box for controlling various JPEG options, such as compression.

Figure 8.7 shows the Export Image as JPEG dialog box you see when you export a JPEG in GIMP. You can see here that you can control the compression ratio for saving JPEG files by adjusting the Quality slider between 1 (low quality, small file size) and 100 (high quality, large file size).

The Export Image as JPEG dialog box.
Figure 8.7 GIMP enables you to reduce file size while still retaining image quality by saving in the JPEG format.

You might want to experiment a bit to see how various JPEG compression levels affect the quality of your images, but 85% quality (or 15% compression) is generally a good compromise between file size (and, therefore, download speed) and quality for most photographic images. If your site caters more to mobile devices, you should opt for a lower quality/higher compression option to reduce download times.

Creating Banners and Buttons

Graphics that you create from scratch, such as banners and buttons, require you to make considerations uniquely different from those that apply to photographs.

The first decision you need to make when you produce a banner or button is how big it should be. Most people accessing the web now have a computer with a screen that is at least 1024 × 768 pixels in resolution, if not considerably larger. Other popular resolutions are 1440 × 900 and 1366 × 768 pixels.

It’s important to design your graphics to fit on mobile devices. In late 2017, the most popular resolution was 360 × 640. While people have larger desktop and laptop screens, they are more and more often viewing web pages on their phones. But in general, you should focus less on the dimensions of your images and more on the file size. An image that is 2000 × 3000 pixels but only 80Kb will load quickly and look great on a mobile device and a desktop screen.

Note

For many years, designing for 800 × 600 screen resolution was the norm. Now, people tend to browse web pages on their phones with resolutions as low as 360 × 640. With responsive web design (RWD) you can create designs that support both the small screens and the big ones. You will learn more about RWD in Lesson 16, “Understanding the Importance of Responsive Web Design,” and how to do it in Lesson 17, “Designing for Mobile Devices.”

Assuming that you target a maximum resolution of 1920 × 1080 pixels, full-size banners and title graphics should be no more than 2000 pixels wide. This gives the images space to be slightly larger than the browser window or smaller, depending on the needs of the design and the device viewing it.

To create a new image in GIMP, go to File and choose New. The Create a New Image dialog box displays (see Figure 8.8). If you aren’t sure how big the image needs to be, just accept the default size of 640 × 480. Or you can choose one of the other predetermined sizes in the Template drop-down, such as Web Banner Common 468 × 60 or Web Banner Huge 728 × 90. Those two settings are conservative, yet perfectly acceptable, interpretations of “common” and “huge” for banners. In this dialog box, you can also enter your own width and height for the new image.

A screenshot displays the drop-down lists under "Templates" of the Create a New Image dialog box. The option, Web banner common 468 cross 60 is selected.
Figure 8.8 You must decide on the size of an image before you start working on it, but you can always resize it later.

For the image’s background color, you should usually choose white to match the background that most web browsers use for web pages (although, as you learned previously, that color can be changed). When you know that you’ll be creating a page with a background other than white, you can choose a different background color for your image. Or you might want to create an image with no background at all, in which case you select Transparency as the background color. When the final, Web-ready image includes a transparent background, the web page (and its background color) behind the image is allowed to show through. In GIMP, select the background color for your new image by opening Advanced Options in the Create a New Image dialog box.

After you enter the width and height of the image in pixels and click OK, you are faced with a blank canvas—an intimidating sight if you’re as art-phobic as most of us! However, so many image-creation tutorials (not to mention entire books) are available to lead you through the process that we’re comfortable leaving you to your own creative devices. This section is all about introducing you to the things you want to keep in mind when creating graphics for use in your sites. This section does not necessarily teach you exactly how to do it because being comfortable with the tool you choose is the first step to mastering it.

Optimizing Images by Reducing or Removing Colors

It’s easy to get hung up on the dimensions of images as you create them, but it’s more important to focus on the file size. More and more people use mobile devices such as smartphones to view the web, and bandwidth limits and charges make large images annoyingly slow to load at best. By optimizing your images as much as possible, you make your pages more mobile friendly. And they will load more quickly on desktops and laptops, too.

One of the most effective ways to reduce the size of an image—and, therefore, its download time—is to reduce the number of colors used in the image. This can drastically reduce the visual quality of some photographic images, but it works great for most banners, buttons, and other icons.

You’ll be glad to know that there is a special file format for images with a limited number of colors, the Graphics Interchange Format (GIF). When you save or export an image as a GIF, you might be prompted to flatten layers or reduce the number of colors by converting to an indexed image because those are requirements for GIFs; check your software’s Help file regarding layers and indexed colors for a full understanding of what you might need to do.

Remember that the GIF image format is designed for images that contain areas of solid colors, such as web page titles and other illustrated graphics; the GIF format is not ideal for photographs; use JPEG or PNG files for photos instead.

PNG (pronounced “ping”) is a useful file format that is supported in all major web browsers. Whereas the GIF image format enables you to specify a single transparent color, which means the background of the web page will show through those areas of an image, the PNG format takes things a step further, enabling you to specify varying degrees of transparency.

You might have seen websites that use background colors or images in their container elements but that also have images present in the foreground that allow the background to show through parts of the foreground graphics. In these cases, the images in the foreground have portions that are transparent so that the images themselves—which are always on a rectangular canvas—do not show the areas of the canvas where the design does not occur. You often want to use these types of partially transparent images to make graphics look good over any background color or background image you have in place.

To make part of an image transparent, the image must be saved in the GIF or PNG file format. As mentioned previously in this lesson, most graphics programs that support the GIF format enable you to specify one color to be transparent, whereas PNG images allow for a range of transparency. Largely because of this transparency range, the PNG format is superior to GIF. All the latest web browsers already support PNG images.

The process of creating a transparent image depends on the type of image you are creating (GIF or PNG) and the graphics software you are using to create it. For instructions, look in your graphics program’s Help files or type “transparent images with [your program here]” into your search engine.

Creating Tiled Background Images

You can use any GIF, JPEG, or PNG image as a background tile within a container element, but before you go off and create a tiled background, especially a highly patterned tiled background, ask yourself what that tiled background adds to the overall look and feel of your website. More importantly, ask yourself whether the text of the site can be read easily when placed over that pattern.

Think about the websites you frequent every day and consider the fact that few sites use tiled, heavily patterned backgrounds on their entire pages. If you restrict your browsing to websites for companies, products, sports teams, or other sites in which information (primarily text) is privileged, the number of sites with tiled, heavily patterned backgrounds decreases even further. The web affords everyone the right of individuality in design, but if you are creating a site for your business, you might want to avoid using a highly patterned background with contrasting colored text.

If you do use a tiled background image for your entire site, remember that tiled images look best when you can’t tell they’re tiled images. In other words, you know you have a good image when the top edge of a background tile matches seamlessly with the bottom edge and the left edge matches with the right.

Figures 8.9 and 8.10 show background tiles in use, both with seamless backgrounds but with varying degrees of effectiveness.

A screenshot shows a sample window with trees in the background image that are darker than and of the same color of the text that overlaps it.
Figure 8.9 This is an example of a seamless background image in which you can tell the background is tiled because you can see several identical shapes.
A screenshot shows a sample window with trees in the background image that are lighter than the text that overlaps it.
Figure 8.10 This is another example of a seamless background image, but you can’t tell that it’s tiled.

Later in this lesson, you’ll learn how to place background images within container elements. Despite our warnings so far in this section, background images can be powerful weapons in your design arsenal—just not when heavily patterned. You can find some great (and freely available) examples of background images—often referred to as textures—at the Subtle Patterns website (www.toptal.com/designers/subtlepatterns/).

Placing Images on a Web Page

To get started with image placement on your website, first move the image file into the same folder as the HTML file or into a directory named images (which you might want to use for easy organization).

Note

It doesn’t matter to the web server, web browser, or end user just where you put your images, as long as you know where they are and use the correct paths in your HTML code.

We prefer to put all our images in a separate images directory or in a subdirectory of a generic assets directory (such as assets/images) so that all the images or other assets, such as multimedia and JavaScript files, are neatly organized.

In this first example, let’s assume you have placed an image called myimage.gif in the same directory as the HTML file you want to use to display it. To display it, insert the following HTML tag at the point in the text where you want the image to appear, using the name of your image file instead of myimage.gif:

<img src="myimage.gif" alt="My Image">

If your image file were in the images directory below the document root, you would use the following code, which you can see now contains the full path to myimage.gif in the images directory:

<img src="/images/myimage.gif" alt="My Image">

Both the src and the alt attributes of the <img> tag are required for valid HTML web pages. The src attribute identifies the image file, and the alt attribute enables you to specify descriptive text about the image. The alt attribute is intended to serve as an alternative to the image if a user is unable to view the image either because it is unavailable or because the user is using a text-only browser or screen reader. You’ll read more on the alt attribute later, in the section “Describing Images with Text.”

Note

The <img> tag is one of the HTML tags that also supports a title attribute; you can use this attribute to describe an image, much like the alt attribute. But while the alt attribute is intended to describe the image, the title provides additional information about the image. You might see the title attribute being used, but please do not use it in place of an alt attribute; doing so will limit your site’s usefulness on many types of devices. And if you don’t include the alt attribute, your HTML will not be valid.

As an example of how to use the <img> tag, Listing 8.2 inserts an image at the top of the page, before a paragraph of text. Whenever a web browser displays the HTML file in Listing 8.2, it automatically retrieves and displays the image file, as shown in Figure 8.11.

Listing 8.2 Using the <img> Tag to Place Images on a Web Page

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>A Spectacular Yosemite View</title>
  </head>
  <body>
    <section>
      <header>
       <h1>A Spectacular Yosemite View</h1>
      </header>   
      <img src="hd.jpg" alt="Half Dome">
      <p><strong>Half Dome</strong> is a granite dome in Yosemite
        National Park, located in northeastern Mariposa County,
        California, at the eastern end of Yosemite Valley. The
        granite crest rises  more than 4,737 ft (1,444 m) above the
        valley floor.</p>
      <p>This particular view is of Half Dome as seen from Washburn
        Point.</p>
    </section>
  </body>
</html>

If you guessed that img refers to “image,” you’re right. Likewise, src refers to “source,” or a reference to the location of the image file. As discussed in the first few lessons, an image is always stored in a file separate from the text of your web page (your HTML file), even though it appears to be part of the same page when viewed in a browser.

A screenshot shows a web browser displaying a JPG image of a granite dome, titled "A Spectacular Yosemite View." Following the image, is a short description.
Figure 8.11 When a web browser displays the HTML shown in Listing 8.2, it renders the hd.jpg image. (Credit: Bernhard Richter/Shutterstock)

Note

You can include an image from any website within your own pages. In those cases, the image is retrieved from the other page’s web server whenever your page is displayed. Although you could do this, you shouldn’t! Not only is it bad manners (and probably a copyright violation) because you are using the other person’s bandwidth for your own personal gain, but it also can make your pages display more slowly. In addition, you have no way of controlling when the image might be changed or deleted.

If you are granted permission to republish an image from another web page, always transfer a copy of that image to your computer and use a local file reference, such as <img src="myimage.jpg"> instead of <img src="http://www.otherserver.com/theirimage.jpg">. This advice is not applicable, however, when you host your images—such as photographs—at a service specifically meant as an image repository, such as Flickr (www.flickr.com). Services such as Flickr provide you with a URL for each image, and each URL includes Flickr’s domain in the address. The same is true if you want to link to images you have taken with mobile applications such as Instagram; these types of services also provide you with a full URL to an image that you can then link to in your own website.

As with the <a> tag used for hyperlinks, you can specify any complete Internet address as the location of an image file in the src attribute of the <img> tag. You can also use relative addresses, such as /images/birdy.jpg or ../smiley.gif.

Describing Images with Text

The <img> tag in Listing 8.2 includes a short text description—in this case, alt="Half Dome". The alt stands for alternate text, which is the message that appears in place of the image itself if it does not load. An image might not load if its address is incorrect, if the Internet connection is very slow and the data has not yet transferred, or if the user is using a text-only browser or screen reader. Figure 8.12 shows one example of alt text used in place of an image. Each web browser renders alt text differently, but the information is still provided when it is part of your HTML document.

A screenshot shows a sample alt message titled "A spectacular Yosemite View." In the place of the image is the alt-text, ‘Half Dome,’ followed by a short description.
Figure 8.12 Users will see alt messages when images do not appear.

Even when graphics have fully loaded and are visible in the web browser, the alt message might appear in a little box (known as a tooltip) whenever the mouse pointer passes over an image. The alt message also helps any user who is visually impaired (or is using a voice-based interface to read the web page).

You must include a suitable alt attribute in every <img> tag on your web pages, keeping in mind the variety of situations in which people might see that message. A very brief description of the image is usually best, but web page authors sometimes put short advertising messages, keyword phrases for SEO, or subtle humor in their alt messages; too much humor and not enough information is frowned upon as being not all that useful. And search engines may view too many keywords as SEO spam. For small or unimportant images, it’s tempting to omit the alt message altogether, but the alt attribute is a required attribute of the <img> tag. If you omit it, it doesn’t mean your page won’t display properly, but it does mean you’ll be in violation of HTML standards. We recommend assigning an empty text message to alt if you absolutely don’t need it (alt=""), which is sometimes the case with small or decorative images.

Specifying Image Height and Width

Because text moves over the Internet much faster than graphics, most web browsers end up displaying the text on a page before they display images. This gives users something to read while they’re waiting to see the pictures, which makes the whole page seem to load faster.

You can make sure that everything on your page appears as quickly as possible and in the right places by explicitly stating each image’s height and width. That way, a web browser can immediately and accurately make room for each image as it lays out the page and while it waits for the images to finish transferring.

For each image you want to include in your site, you can use your graphics program to determine its exact height and width in pixels. You might also be able to find these image properties by using system tools. For example, in Windows, you can see an image’s height and width by right-clicking the image, selecting Properties, and then selecting Details. When you know the height and width of an image, you can include its dimensions in the CSS, like this:

<img src="myimage.gif" alt="Fancy Pic" style="width:200px;height:100px;">

Note

The height and width specified for an image don’t have to match the image’s actual height and width. A web browser tries to squish or stretch the image to display whatever size you specify. The best way to adjust the dimensions of your images is to set width to a percentage of the container and height to auto, as shown here:

style="width:100%; height:auto;"

This ensures that the image will fit in the design width and the aspect ratio will remain the same as the original size.

Just as with other design elements such as background color or font size, you should not specify the exact dimensions of images in the HTML. Instead, you should set the width and height by using CSS style sheets. You can use any measurement you want for the width and height, but to ensure that the image doesn’t look bad, it’s best to set one of the dimensions to auto.

Note

HTML5 has introduced the <picture> element and the srcset and sizes attributes. The <picture> element lets designers control which image should be displayed to which browser. And the srcset and sizes attributes define multiple image resources for browsers of different sizes. These will be discussed in more detail in Lesson 17. These new features are well supported in modern browsers and give designers more options for images.

Aligning Images

Just as you can align text on a page, you can align images on a page by using special attributes. You can align images both horizontally and vertically with respect to text and other images that surround them.

Horizontal Image Alignment

As discussed in Lesson 6, “Working with Fonts, Text Blocks, Lists, and Tables,” you can use the text-align CSS property to align content within an element as centered, aligned with the right margin, or aligned with the left margin. These style settings affect both text and images, and they can be used in any block element, such as <p>.

Like text, images are normally lined up with the left margin unless another alignment setting indicates that they should be centered or right-justified. In other words, left is the default value of the text-align CSS property.

You can also wrap text around images by applying the float CSS property to the <img> tag.

In Listing 8.3, <img style="float:left;"> aligns the first image to the left and wraps text around the right side of it, as you might expect. Similarly, <img style="float:right;"> aligns the second image to the right and wraps text around the left side of it. Figure 8.13 shows how these images align on a web page. There is no concept of floating an image to the center because there would be no way to determine how to wrap text on each side of it.

Listing 8.3 Using float Style Properties to Align Images on a Web Page

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>More Spectacular Yosemite Views</title>
  </head>
  <body>
    <section>
      <header>
        <h1>More Spectacular Yosemite Views</h1>
      </header>
      <p><img src="elcap_sm.jpg" alt="El Capitan"
      style="float:left;padding:12px;width:100px;height:75px;"><strong>El
      Capitan</strong> is a 3,000-foot (910 m) vertical rock formation
      in Yosemite National Park, located on the north side of Yosemite
      Valley, near its western end. The granite monolith is one of the
      world's favorite challenges for rock climbers. The formation was
      named "El Capitan" by the Mariposa Battalion when it explored the
      valley in 1851.</p>
      <p><img src="tunnelview_sm.jpg" alt="Tunnel View"
      style="float:right;padding:12px;width:100px;height:80px;"><strong>Tunnel
      View</strong> is a viewpoint on State Route 41 located directly east
      of the Wawona Tunnel as one enters Yosemite Valley from the south.
      The view looks east into Yosemite Valley including the southwest face
      of El Capitan, Half Dome, and Bridalveil Falls. This is, to many, the
      first views of the popular attractions in Yosemite.</p>
    </section>
  </body>
</html>

A screenshot shows the alignment of the images in the "More spectacular Yosemite views" web page. The first image appears on the left followed by the corresponding text, while the next image appears on the right and is preceded by its text.
Figure 8.13 Showing the image alignment from Listing 8.3.

Note

Notice the addition of padding in the style attribute for both <img> tags used in Listing 8.3. This padding provides some breathing room between the image and the text—12 pixels on all four sides of the image. You’ll learn more about padding in Lesson 9, “Working with Margins, Padding, Alignment, and Floating.”

Vertical Image Alignment

Sometimes you want to insert a small image in the middle of a line of text, or you want to put a single line of text next to an image as a caption. In either case, having some control over how the text and images line up vertically would be handy. Should the bottom of the image line up with the bottom of the letters, or should the text and images all be arranged so that their middles line up? You can choose between these and several other options:

  • Image To line up the top of an image with the top of the tallest image or letter on the same line, use this:

    <img style="vertical-align:text-top;">

  • Image To line up the bottom of an image with the bottom of the text, use this:

    <imgstyle="vertical-align:text-bottom;">

  • Image To line up the middle of an image with the overall vertical center of everything on the line, use this:

    <img style="vertical-align:middle;">

  • Image To line up the bottom of an image with the baseline of the text, use this:

    <imgstyle="vertical-align:baseline;">

Note

The vertical-align CSS property also supports the values top and bottom, which can align images with the overall top or bottom of a line of elements, regardless of any text on the line.

All four of these options are used in Listing 8.4 and displayed in Figure 8.14. Four thumbnail images are now listed vertically down the page, and descriptive text appears next to each image. Various settings for the vertical-align CSS property are used to align each image and its relevant text. This is certainly not the most beautiful page, but it should help make the various alignments clear.

Listing 8.4 Using vertical-align Styles to Align Text with Images

<!doctype html>
  <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>Small But Mighty Spectacular Yosemite Views</title>
    </head>
    <body>
      <section>
        <header>
          <h1>Small But Mighty Yosemite Views</h1>
        </header>
        <p><img src="elcap_sm.jpg" alt="El Capitan"
        style="width:100px;height:75px;vertical-align:text-top;"><strong>El
        Capitan</strong> is a 3,000-foot (910 m) vertical rock formation
        in Yosemite National Park.</p>
        <p><img src="tunnelview_sm.jpg" alt="Tunnel View"
        style="width:100px;height:80px;vertical-align:text-bottom;">
        <strong>Tunnel View</strong> looks east into Yosemite Valley.</p>
        <p><img src="upperyosefalls_sm.jpg" alt="Upper Yosemite Falls"
        style="width:87px;height:100px;vertical-align:middle;"><strong>Upper
        Yosemite Falls</strong> are 1,430 ft and are among the twenty highest
        waterfalls in the world. </p>
        <p><img src="hangingrock_sm.jpg" alt="Hanging Rock"
        style="width:100px;height:75px;vertical-align:baseline;">
        <strong>Hanging Rock</strong>, off Glacier Point, used to be a popular
        spot for people to, well, hang from. Crazy people.</p>
      </section>
    </body>
</html>

Note

If you don’t assign any vertical-align CSS property in an <img> tag or class used with an <img> tag, the bottom of the image will line up with the baseline of any text next to it. This means you never have to use vertical-align:baseline; because it is assumed by default. However, if you specify a margin for an image and intend for the alignment to be a bit more exact in relationship to the text, you might want to explicitly set the vertical-align property to text-bottom.

A screenshot shows an example of vertical image alignment using the "Small But Mighty Yosemite Views" webpage. The photographs are on the left, one below the other with descriptive text to the right of each one.
Figure 8.14 Showing the vertical image alignment options used in Listing 8.4.

Turning Images into Links

You probably noticed in Figure 8.11 that the image on the page is quite large. This is fine in this particular example, but it isn’t ideal when you’re trying to present multiple images. It makes more sense to create smaller image thumbnails that link to larger versions of each image. Then you can arrange the thumbnails on the page so that visitors can easily see all the written content, even if they see only a smaller version of the actual (larger) image. Using thumbnails is one of the many ways you can use image links to spice up your pages.

To turn any image into a clickable link to another page or image, you can use the <a> tag that you learned about in Lesson 7 to make text links. Listing 8.5 contains the code to display thumbnails of images within text, with those thumbnails linking to larger versions of the images. To ensure that the user knows to click the thumbnails, the image and some helper text are enclosed in a <div>, as shown in Figure 8.15.

Listing 8.5 Using Thumbnails for Effective Image Links

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>More Spectacular Yosemite Views</title>
    <style>
    div.imageleft {
      float: left;
      text-align: center;
      font-size: 10px;
      font-style: italic;
    }
    div.imageright {
      float: right;
      text-align: center;
      font-size: 10px;
      font-style: italic;
    }
    img {
      padding: 6px;
      border: none;
    }
    </style>
  </head>
  <body>
    <section>
      <header>
        <h1>More Spectacular Yosemite Views</h1>
      </header>
      <div class="imageleft">
        <a href="http://www.flickr.com/photos/nofancyname/614253439/"><img
        src ="elcap_sm.jpg" alt="El Capitan"
        style="width:100px; height:75px;"></a>
        <br>click image to enlarge
      </div>
      <p><strong>El Capitan</strong> is a 3,000-foot (910 m) vertical rock
      formation in Yosemite National Park, located on the north side of
      Yosemite Valley, near its western end. The granite monolith is one
      of the world's favorite challenges for rock climbers. The formation
      was named "El Capitan" by the Mariposa Battalion when it explored
      the valley in 1851.</p>
      <div class="imageright">
        <a href="http://www.flickr.com/photos/nofancyname/614287355/"><img
        src="tunnelview_sm.jpg" alt="Tunnel View"
        style="width:100px; height:80px;"></a>
        <br>click image to enlarge
      </div>
      <p><strong>Tunnel View</strong> is a viewpoint on State Route 41
      located directly east of the Wawona Tunnel as one enters Yosemite
      Valley from the south. The view looks east into Yosemite Valley
      including the southwest face of El Capitan, Half Dome, and
      Bridalveil Falls. This is, to many, the first views of the
      popular attractions in Yosemite.</p>
    </section>   
  </body>
</html>

A screenshot shows an example of using thumbnails as links with the "More Spectacular Yosemite views" webpage. Two images on the top left and bottom right have links below them that read, "Click image to enlarge."
Figure 8.15 Using thumbnails as links improves the layout of a page that uses large images.

The code in Listing 8.5 uses additional styles that are explained in more detail in other lessons, but you should be able to figure out the basics:

  • Image The <a> tags link these particular images to larger versions, which, in this case, are stored on an external server (at Flickr).

  • Image The <div> tags, and their styles, are used to align those sets of graphics and caption text (and also include some padding).

Unless instructed otherwise, web browsers display a colored border around the edge of each image link. As with text links, the rectangle usually appears blue for links that haven’t been visited recently and purple for links that have been visited recently—unless you specify different-colored links in your style sheet. Because you seldom, if ever, want this unsightly line around your linked images, you should usually include style="border:none;" in any <img> tag within a link. In this instance, the border:none style is made part of the style sheet entry for the img element because we use the same styles twice.

When you click one of the thumbnail images on the sample page shown, the link opens in the browser, as shown in Figure 8.16.

A screenshot shows the result of clicking a linked thumbnail. The output is a larger image opened in a different webpage.
Figure 8.16 Clicking a linked thumbnail image opens the target of the link.

Using Background Images

As you learned earlier in this lesson, you can use background images to act as a sort of wallpaper in a container element so that the text or other images appear on top of this underlying design.

The basic CSS properties that work together to create a background are listed here:

  • Image background-color—Specifies the background color of the element. Although it is not image related, it is part of the set of background-related properties. If an image is transparent or does not load, the user will see the background color instead.

  • Image background-image—Specifies the image to use as the background of the element, using the following syntax: url('imagename.gif').

  • Image background-repeat—Specifies how the image should repeat, both horizontally and vertically. By default (without specifying anything), background images repeat both horizontally and vertically. Other options are repeat (same as default), repeat-x (horizontal), repeat-y (vertical), and no-repeat (only one appearance of the graphic).

  • Image background-position—Specifies where the image should be initially placed, relative to its container. Options include top-left, top-center, top-right, center-left, center-center, center-right, bottom-left, bottom-center, bottom-right, and specific pixel and percentage placements.

When specifying a background image, you can put all these specifications together into the background property, like so:

body {
   background: #ffffff url('imagename.gif') no-repeat top right;
}

In the preceding style sheet entry, the body element of the web page will be white and will include a graphic named imagename.gif at the top right. Another use for the background property is to create custom bullets for your unordered lists. To use images as bullets, first define the style for the <ul> tag as shown here:

ul {
  list-style-type: none;
  padding-left: 0;
  margin-left: 0;
}

Next, change the declaration for the <li> tag to this:

li {
  background: url(mybullet.gif) left center no-repeat
}

Make sure that mybullet.gif (or whatever you name your graphic) is on the web server and accessible; in this case, all unordered list items will show your custom image instead of the standard filled-disc bullet.

We return to the specific use of background properties in Part III, “Advanced Web Page Design with CSS,” when using CSS for overall page layouts.

Using Image Maps

Sometimes you want to use an image as navigation—but beyond the simple button-based or link-based navigation that you often see in websites. For example, perhaps you have a website with medical information, and you want to show an image of the human body that links to pages that provide information about various body parts. Or you might have a website that provides a world map that users can click to access information about countries. You can divide an image into regions that link to different documents, depending on where users click within that image. This is called an image map, and any image can be made into an image map.

Why Image Maps Aren’t Always Necessary

The first point to know about image maps is that you probably won’t need to use them except in very special cases. It’s almost always easier and more efficient to use several ordinary images that are placed directly next to one another and provide a separate link for each image.

For example, Figure 8.17 shows a web page that displays 12 different corporate logos; this example is a common type of web page in the business world, in which you give a little free advertisement to your partners. You could present these logos as one large image and create an image map that provides links to each of the 12 companies. Users could click each logo in the image to visit each company’s site. But every time you wanted to add a new logo to the image map, you would have to modify the entire image and remap the hotspots—which would not be a good use of anyone’s time. In such a case, when an image map is not warranted, you simply display the images on the page as in this example by using 12 separate images (1 for each company) and having each image include a link to the particular company.

A screenshot of the BAWSI webpage. The main body area shows 12 different logos (images) in a four cross three grid layout.
Figure 8.17 A web page with 12 different logos; this could be presented as a single image map or divided into 12 separate pieces.

Using an image map is the best choice for an image that has numerous parts, is oddly arranged, or has a design that is itself too complicated to divide into separate images. Figure 8.18 shows an image that is best suited as an image map—a public domain image provided by the U.S. CIA of the standard time zones of the world.

A world map marked with the different time zones around the globe. The time zones are indicated by vertical lines. They mark the boundary of each time zone across continents.
Figure 8.18 This image wouldn’t respond well to being sliced up into perfectly equal parts; better make it an image map.

Mapping Regions Within an Image

To create any type of image map, you need to figure out the numeric pixel coordinates of each region within the image that you want to turn into a clickable link. These clickable links are also known as areas. Your graphics program might provide you with an easy way to find these coordinates. Or you might want to use a standalone image mapping tool such as Mapedit (https://boutell.com/mapedit/) or an online image map maker such as the one at www.image-maps.com. In addition to helping you map the coordinates, these tools provide the HTML code necessary to make the maps work.

Using an image mapping tool is often as simple as using your mouse to draw a rectangle (or a custom shape) around the area you want to be a link. Figure 8.19 shows the result of one of these rectangular selections, as well as the interface for adding the URL and the title or alternate text for this link. Several pieces of information are necessary for creating the HTML for your image map: coordinates, target URL, and alternate text for the link.

A screenshot shows an example of  using the image mapping tool.
Figure 8.19 Using an image mapping tool to create linked areas of a single graphic.

Creating the HTML for an Image Map

If you use an image map generator, it will provide the necessary HTML for creating the image map. However, it is a good idea to understand the parts of the code so that you can check it for accuracy. The following HTML code is required to start any image map:

<map name="mapname">

Keep in mind that you can use whatever name you want for the name of the <map> tag, although it helps to make it as descriptive as possible. Next, you need an <area> tag for each region of the image. Following is an example of a single <area> tag that was produced by the actions shown in Figure 8.19:

<area shape="rect" coords="1,73,74,163"
   href="http://en.wikipedia.org/wiki/Alaska"
    alt="Alaska"   title="Alaska">

This <area> tag has five attributes, which you use with every area you describe in an image map:

  • Image shape—Indicates whether the region is a rectangle (shape="rect"), a circle (shape="circle"), or an irregular polygon (shape="poly").

  • Image coords—Gives the exact pixel coordinates for the region. For rectangles, give the x,y coordinates of the upper-left corner followed by the x,y coordinates of the lower-right corner. For circles, give the x,y center point followed by the radius in pixels. For polygons, list the x,y coordinates of all the corners in a connect-the-dots order.

    Here is an example of a mapped polygon (which can get a little crazy looking):

    <areashape="poly" coords="233,0,233,20,225,22,225,101,216,121,212,154,212,167,212, 181,222,195,220,209,226,214,226,234,232,252,224,253,223,261,231, 264,232,495,254,497,274,495,275,482,258,463,275,381,270,348,257, 338,266,329,272,313,271,301,258,292,264,284,262,262,272,263,272, 178,290,172,289,162,274,156,274,149,285,151,281,134,272,137,274,3" href="http://en.wikipedia.org/wiki/Eastern_Time_Zone" alt="Eastern Time Zone" title="Eastern Time Zone">

  • Image hre—Specifies the location to which the region links. You can use any address or filename that you would use in an ordinary <a> link tag.

  • Image alt—Enables you to provide a piece of text that describes the shape; as you learned previously, providing this text is important to users browsing with text-only browsers or screen readers.

  • Image title—Ensures that tool tips containing the information are also visible when the user accesses the designated area.

Each distinct clickable region in an image map must be described as a single area, which means that a typical image map consists of a list of areas. After you’ve coded the <area> tags, you are done defining the image map, so wrap things up with a closing </map> tag.

The last step in creating an image map is wiring it up to the actual map image. The map image is placed on the page using an ordinary <img> tag. However, an extra usemap attribute is coded, like this:

<img src="timezonemap.png" usemap="#timezonemap"
  style="border:none; width:977px;height:498px "
   alt="World Timezone Map">

When specifying the value of the usemap attribute, use the name you put in the id of the <map> tag (and don’t forget the # symbol). Also include the style attribute to specify the height and width of the image and to turn off the border around the image map, which you might or might not elect to keep in image maps of your own.

Listing 8.6 shows the complete code for a sample web page containing the map graphic, its image map, and a few mapped areas.

Listing 8.6 Defining the Regions of an Image Map with <map> and <area> Tags

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Testing an Image Map</title>
  </head>
  <body>
    <section>
      <header>
        <h1>Testing an Image Map</h1>
      </header>
      <div style="text-align:center;">
        Click on an area to learn more about
        that location or time zone.<br>
        <imgsrc="timezonemap.png"usemap="#timezonemap"
        style="border:none;width:977px;height:498px;"
        alt="World Timezone Map">
      </div>
    </section>
    <mapname="timezonemap" id="timezonemap">
      <area shape="poly" coords="233,0,233,20,225,22,225,101,216,121,212,
      154,212,167,212,181,222,195,220,209,226,214,226,234,232,252,224,
      253,223,261,231,264,232,495,254,497,274,495,275,482,258,463,275,
      381,270,348,257,338,266,329,272,313,271,301,258,292,264,
      284,262,262,272,263,272,178,290,172,289,162,274,156,274,
      149,285,151,281,134,272,137,274,3"
      href="http://en.wikipedia.org/wiki/eastern_time_zone"
      alt="Eastern Time Zone" title="Eastern Time Zone">
      <area shape="rect" coords="1,73,74,163 "
      href="http://en.wikipedia.org/wiki/Alaska"
      alt="Alaska" title="Alaska">
    </map>
  </body>
</html>

Figure 8.20 shows the image map from Listing 8.6 in action. When you hover the mouse over an area, the alt or title text for that area—in this example, Eastern Time Zone—is displayed on the image map.

A screenshot shows the result of using an Imagemap. It shows the world map with time zones. At the top of the map, a text reads: Click on an area to learn more about that location or time zone.
Figure 8.20 The image map defined in Listing 8.6, as it displays on the web page.

Note

One method of producing mapped images relies solely on CSS, not the HTML <map> tag. You will learn more about this in Lesson 11, “Using CSS to Do More with Lists, Text, and Navigation.”

Linking to Multimedia Files

Let’s move away from static images for a moment and move into more exciting multimedia such as audio and video. The simplest and most reliable option for incorporating a video or audio file into your website is to simply link it in with an <a> tag, exactly as you would link to another HTML file.

For example, you could use the following line to offer an MOV video of a cute chickadee:

<a href="chickadee.mov">View a cute chickadee!</a>

When the user clicks the words View a cute chickadee!, the chickadee.mov QuickTime video file is transferred to his or her computer from your web server. Whichever helper application or plug-in the user has installed automatically starts as soon as the file has finished downloading. If no compatible helper or plug-in can be found, the web browser offers the user a chance to download the appropriate plug-in or save the video on the hard drive for later viewing.

Note

In case you’re unfamiliar with helper applications (helper apps for short), they are the external programs that a web browser calls on to display any type of file it can’t handle on its own. Generally, the helper application associated with a file type is called on whenever a web browser can’t display that type of file on its own.

Plug-ins are a special sort of helper application installed directly into a web browser. They enable you to view multimedia content directly in the browser window. Most browsers have video plugins installed by default.

Listing 8.7 contains the code for a web page that uses a simple image link to play a video in Windows Media file format. In addition to the image link, a link is placed within the text to provide context for the user.

Listing 8.7 Linking an Image to a Windows Media Video

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>This Chickadee Thinks It’s a Hummingbird!</title>
  </head>

  <body>
    <h1>This Chickadee Thinks It’s a Hummingbird!</h1>
    <div style="border-style:none; float:left; padding:12px;">
      <a href="chickadee.wmv"><img src="projector.gif"
        alt="Chickadee Video"></a>
    </div>
    <p>Chickadees have to eat too! But most don’t eat hummingbird
      nectar.</p>   
    <p>Click <a href="chickadee.wmv">here</a> or on the projector graphic to
      see a movie clip of this chickadee in action.</p>
  </body>
</html>

This code simply uses the projector.gif GIF image as a link to the chickadee.wmv video clip. Figure 8.21 shows the chickadee sample page with the projector image in view. When the image is clicked, the Windows Media Player is invoked and begins to play the movie.

A screenshot shows an example for invoking an external application from a webpage. The projector.gif on the left is shown to be clicked and the browser window is overlapped on the right by another window playing a video.
Figure 8.21 The projector.gif GIF image is used as an image link to a Windows Media file that launches an external helper application. Note that not all computers support WMV files.

To view the video, you need only click the animated projector (or the text link in the paragraph). This action results in the browser either playing the video with the help of a plug-in (if one is found that can play the clip) or deferring to a suitable helper application or downloading the image to the hard drive.

If you change the link from chickadee.wmv (Windows Media) to chickadee.mov (QuickTime), your browser handles the link differently. Instead of launching another program, the QuickTime plug-in enables you to view the movie clip directly in the browser window (see Figure 8.22).

A screenshot shows a browser playing a video using the Quick Time browser plug-in.
Figure 8.22 When you follow the image link, the chickadee.mov QuickTime movie is played using the QuickTime browser plug-in.

Note

If your browser has no support for QuickTime, you can download the QuickTime player free from Apple at www.apple.com/quicktime/. Even if you do have QuickTime installed, some browsers play QuickTime movies differently based on whether a plug-in is installed. For example, on my Windows computer, Internet Explorer and Firefox both play QuickTime movies directly in the browser window via a plug-in, whereas Opera launches QuickTime as a helper application.

As you might have guessed, this approach of using a simple link to play multimedia files offers the best backward compatibility because the browser bears all the responsibility of figuring out how to play a multimedia clip. The downside to this is that you don’t have much control over how a clip is played, and the clip won’t play directly in the context of a page.

Embedding Multimedia Files

HTML5 introduced two new tags for embedding media files in a web page: <video> and <audio>. These tags are widely supported in both desktop and mobile browsers and are used like the <img> tag to embed either video or audio files. These tags also use the <source> tag to define the source files for the video or audio to play.

Using the <video> Element to Play Video on Web Pages

Embedding a video file into a web page produces a set of software controls that enable the file to be played directly; no secondary window is necessary, and there’s no need to navigate away from the page you are on. Following is code to embed a chickadee video using the <video> tag:

<video controls style="width: 400px; height: auto;"
  src="chickadee.wmv" type="video/x-ms-wmv">
  <p>Your browser does not support HTML5 video.</p>
</video>

The <video> element contains the fallback text Your browser does not support HTML5 video. that is displayed only if the tag doesn’t display—much like the alt attribute in the <img> tag. In most browsers, the video will display, and many designers don’t include this alternative text.

That is all you need to embed a video file, but that HTML won’t work reliably across computers because the video is embedded as a Windows Media file. You could change the HTML to just point to the MP4 file, you could convert the file to an MP4 file, or you could use the <source> tag to define alternatives, like so:

<video controls>
  <source src="images/chickadee.wmv" type="video/x-ms-wmv">
  <source src="images/chickadee.mp4" type="video/mp4">
  <p>Your browser does not support HTML5 video.</p>
</video>

Caution

There are many video codecs and containers out there, including MOV, AVI, Flash, and WMV. But there are only three that work reliably in web pages:

  • Image MP4 or H264 has the best support with all modern browsers able to play these files.

  • Image WebM is well supported by Firefox and Chrome. It is partially supported in Edge and works with installed codecs for Safari and Internet Explorer.

  • Image Ogg or Ogg/Theora is supported by Firefox and Chrome, and it will be supported by Edge, but doesn’t have good support in other browsers.

It’s best to convert any video files you have to MP4. Search your favorite search engine to find free online converters.

You can see the result of this code in Figure 8.23. The <source> element allows you to define as many source files as you need or want. You still have to create and upload those videos, but the browsers will only download and use the one they support. This makes your videos more cross-compatible.

Note

There are many different video formats you can use. Most designers use MP4 because it is supported across all modern browsers, including mobile devices. Other formats you might see on web pages include WebM, HEVC, and OggTheora or OggV.

A screenshot shows an example of embedding video in a webpage.
Figure 8.23 The <video> tag enables you to embed a video clip on a web page.

The width and height style properties of the <video> element determine the size of the embedded player. Some browsers automatically size the embedded player to fit the content if you leave these off, whereas others don’t show anything. Play it safe by always defining the dimensions of the video to suit the multimedia content being played. Just as with images, you can set the width to a relative value such as 100% of the container width and then set the height to auto so that it isn’t distorted.

The other attribute most designers use on the <video> tag is controls. This tells the browser to display the video with play/pause control buttons. But there are a couple other attributes that can be useful:

  • Image preload—Has three possible values: none, auto, and metadata. Use none if you do not want to buffer the file, use auto to buffer the file, and use metadata if you want to buffer only the metadata for the file.

  • Image loop—Tells the browser to start the video from the beginning when it gets to the end.

  • Image poster—Points to an image file that is shown when the video isn’t available, such as when it is still downloading.

  • Image autoplay—Causes the video to start playing as soon as it is ready.

Listing 8.8 shows the relevant code for the chickadee web page, and you can see the <video> element as it appears in context.

Listing 8.8 Using a <video> Element to Directly Embed a Video Clip

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Chickadee Wants Food!</title>
    <style>
      video {
        width: 50%; height: auto; float: left; padding: 1rem;
      }
    </style>
  </head>
  <body>
    <h1>Chickadee Wants Food!</h1>
    <video controls>
      <source src="images/chickadee.wmv" type="video/x-ms-wmv">
      <source src="images/chickadee.mp4" type="video/mp4">
      <p>Your browser does not support HTML5 video.</p>
    </video>
    <p>All birds eat, but this chickadee would like you to know
    that it's not happy with hummingbird food as the only option.
    </p>
    <p>Chickadees also drink the hummingbird water at times, so if
    you want to feed only hummers, you should watch the other birds.
    </p>
  </body>
</html>

Using the <audio> Element for Audio Playback

In the preceding section, you learned about how to embed video files with the HTML5 <video> element. The <audio> element works in much the same way. You just put the <audio> element where you want your player to display, and the browser will include it.

Listing 8.9 shows how to use the <audio> element to embed an audio file that will be played by the browser. The <audio> element is quite simple and requires only one attribute: src, or the location of the resource you want to play. However, as you see in Listing 8.9, you’ll probably want to use a few other handy attributes.

Listing 8.9 Using the <audio> Element to Embed and Play an Audio File

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Let's Hear Some Music</title>
  </head>
  <body>
    <h1>Let's Hear Some Music</h1>
    <p>Better yet, let's use the HTML5 &lt;audio&gt; element
    to do so!</p>
    <audio
          src="manhattan_beach.mp3"
          preload="auto"
          controls
          autoplay
          loop>
          <p>Your browser does not support the audio element.</p>
    </audio>
   </body>
</html>

Note

Notice the inclusion of a message to users inside the <audio> element. Although current versions of all major browsers support the <audio> element, just as with the <video> element, if a user’s browser does not support it, that user will instead see the message within the <p></p> tags. The message can be any combination of HTML, including links, images, or scripts.

In addition to the src attribute, which, in this case, has the value manhattan_beach.mp3 because that is the name of the audio file we want to play, we’re using four other attributes in this <audio> element:

  • Image preload—Has three possible values: none, auto, and metadata. Use none if you do not want to buffer the file, use auto to buffer the file, and use metadata if you want to buffer only the metadata for the file.

  • Image controls—If present, shows the controls for the audio player.

  • Image autoplay—If present, plays the file as soon as it loads.

  • Image loop—If present, continues to play the file repeatedly until it is manually stopped.

Figure 8.24 shows the page in Listing 8.9 as rendered by the Chrome web browser.

A screenshot shows the output of "audio" element. A horizontal bar denoting an audio player, with pause, audio position navigator, time, and volume buttons.
Figure 8.24 Using the <audio> element to play a sound file.

In practice, you probably wouldn’t want to automatically play and loop a sound file in your website as doing so is typically considered a particularly negative user experience. However, if you do automatically play a sound file (please don’t!), be sure to include the player controls so that users can immediately turn off the sound.

Just as with videos, you should define the MIME type for the audio files you want to include. Following are the MIME types for several popular audio formats you might want to use in your web pages:

  • Image WAV audio—audio/vnd.wave

  • Image MP3 audio—audio/mpeg

  • Image MP4 audio—audio/mp4

Additional Tips for Using Multimedia

Before you add video, audio, or animations to your website, ask yourself whether you really should do so. When you use these types of multimedia, be sure to do so for a reason. Gratuitous sound and video, just like gratuitous images, can detract from your overall message. Then again, if your message is “Look at the videos I’ve made” or “Listen to my music and download some songs,” then multimedia absolutely must play a role in your website.

Keep a few additional tips in mind:

  • Image Don’t include multimedia in a page and set it to automatically play when the page loads. Always give users the option to start (and stop) your sound or video. If you’re using a video background, make sure the sound is muted or removed; video is distracting, and sound is often more so.

  • Image When providing files for direct download, give users a choice of file type. Don’t limit yourself to providing multimedia content playable by only one type of player on only one operating system. Use the <source> tag to provide multiple options on your embedded media as well.

  • Image Multimedia files are larger than typical graphics and text files, which means you need to have the space on your web server to store them, as well as the bandwidth allotment to transfer them to whomever requests them via your website. Check with your hosting provider if you plan to serve more than a few videos on your website; it may have restrictions or offer deals for better hosting of large files.

  • Image If your site is entirely audio or video and offers very little by way of text or graphics, understand that a certain segment of your audience won’t see or hear what you want to present because of the limitations of their system or bandwidth. Provide these users with additional options to get your information. This is also good for accessibility.

  • Image Leverage free online video hosting services, such as YouTube (www.youtube.com). Not only does YouTube provide storage for your video clips, it also gives you the code necessary to embed the video in your own web page.

Summary

In this lesson, you learned a few best practices for color use, and you learned how to use the color wheel to find colors that will complement your text. In addition, you learned about hexadecimal notation for colors—where all colors are expressed in notations related to the amount of red, green, and blue in them—and saw how hexadecimal notation enables you to apply nuanced colors to your elements. You also learned how to add transparency to your colors with the RGBa color model. More importantly, you learned about the three color-related style properties that you can use to apply color to container backgrounds, borders, and text using CSS. In addition, you learned the basics of preparing graphics for use on web pages. You saw that this is a complex topic, and you learned just enough in this lesson to whet your appetite. The examples in this lesson use the popular (and free!) GIMP software package, but feel free to use the graphics software that best suits your needs. Among the actions you learned were how to crop, resize, and tweak image colors, and you also learned about the different file formats. You must keep in mind many considerations when including graphics in your site, including graphic size and resolution, as well as how to use transparency, animated GIFs, and tiled backgrounds.

After creating images, you also learned how to use images in your web pages. You learned how to place them in your pages using the <img> tag and how to include a short text message that appears in place of the image as it loads and that also appears whenever users move the mouse pointer over the image. You also learned how to control the horizontal and vertical alignment of each image and how to wrap text around the left or right of an image. To make your pages more interactive, you learned how to use images as links—either by using the <a> tag around the images or by creating image maps. Finally, you learned how to embed video and sound in a web page. You learned how to use a simple link to a multimedia file, which is the most broadly supported but least flexible option for playing media content. You then learned how to use the <video> and <source> elements to embed a media player directly in a web page. You also learned about the <audio> element in HTML5, which enables the browser to render audio files. In addition, you got some tips for including multimedia in your pages.

Table 8.1 summarizes the tags and attributes covered in this lesson.

Table 8.1 Tags and Attributes Covered in Lesson 8

Tag

Function

<img>

Places an image file within the page.

Attribute/Style Function

style="background-color:color;"

Sets the background color of an element (such as <body>, <p>, <div>, <blockquote>, and other containers).

style="color:color;"

Sets the color of text within an element.

style="border:size type color;"

Sets the color of the four borders around an element. Border colors cannot be used without also specifying the width and type of the border.

src="address"

Gives the address or filename of the image.

alt="altdescription"

Gives an alternative description of the image that is displayed in place of the image, primarily for users who can’t view the image itself.

Tag

Function

title="title"

Specifies a text message that is displayed as an image title, typically in a small pop-up box (tooltip) over the image.

style="width:length;"

Specifies the width of the image (in pixels).

style="height:length;"

Specifies the height of the image (in pixels).

style="border:size type color;"

Gets rid of the border around the image if the image is serving as a link.

style="vertical-align:alignment;"

Aligns the image vertically to text-top, top, text-bottom, bottom, middle, or baseline.

style="float:location;"

Floats the image to one side so that text can wrap around it. Possible values are left, right, and none (default).

Tag

Function

<map></map>

Defines a client-side image map referenced by <img usemap="...">. Includes one or more <area> tags.

<area>

Defines a clickable link within a client-side image map.

Attribute/Style

Function

usemap="name"

Defines the name of an image map for client-side image mapping. Used with <map> and <area>.

shape="value"

Within the <area> tag, specifies the shape of the clickable area. Valid options for this attribute are rect, poly, and circle.

coords="values"

Within the <area> tag, specifies the coordinates of the clickable region within an image. Its meaning and setting vary according to the type of area.

href="linkurl"

Within the <area> tag, specifies the URL that should be loaded when the area is clicked.

Tag

Function

<audio></ audio >

Plays an audio file natively in the browser.

Attribute/Style

Function

src="mediaurl"

Gives the URL of the file to embed.

preload="preloadtype"

Tells whether to preload the media file. Options are none, auto, and metadata.

controls

Instructs the browser to show the audio player controls.

autoplay

Instructs the browser to play the file when it has finished loading.

loop

Instructs the browser to play the file until it is explicitly stopped.

Tag

Function

<video></ video >

Plays a video file natively in the browser.

Attribute/Style

Function

src="mediaurl"

Gives the URL of the file to embed.

preload="preloadtype"

Tells whether to preload the media file. Options are none, auto, and metadata.

style="width:length;"

Specifies the width of the embedded object, in pixels.

style="height:length;"

Specifies the height of the embedded object, in pixels.

controls

Instructs the browser to show the video player controls.

autoplay

Instructs the browser to play the file when it has finished loading.

loop

Instructs the browser to play the file until it is explicitly stopped.

Q&A

Q. I’ve produced graphics for printing on paper. Are web page graphics any different?

A. Yes. In fact, many of the rules for print graphics are reversed on the Web. Web page graphics should be low resolution to keep the file size small, whereas print graphics should be the highest resolution possible. White washes out black on computer screens, whereas black bleeds into white on paper. Also, someone might stop a web page from loading when only half the graphics have been downloaded, which isn’t a consideration when one is looking at images in print. Try to avoid falling into old habits if you’ve done a lot of print graphics design.

Q. I used the <img> tag just as you advised, but when I view the page, all I see is a little box with some shapes in it. What’s wrong?

A. The broken image icon you’re seeing can mean one of two things: Either the web browser couldn’t find the image file or the image isn’t saved in a format the browser recognizes. To solve these problems, first check to make sure the image is where it is supposed to be. If it is, then open the image in your graphics editor and save it again as a GIF, JPEG, or PNG.

Q. What happens if I overlap areas on an image map?

A. You are allowed to overlap areas on an image map. Just keep in mind that, in the determination of which link to follow, one area has precedence over the other area. Precedence is assigned according to which areas are listed first in the image map. For example, the first area in the map has precedence over the second area, which means that a click in the overlapping portion of the areas will link to the first area. If you have an area within an image map that doesn’t link to anything (known as a dead area), you can use this overlap trick to deliberately prevent this area from linking to anything. To do this, just place the dead area before other areas so that the dead area overlaps them and then set its href attribute to "" (blank).

Q. I hear a lot about streaming video and audio. What does that mean?

A. In the past, video and audio files took minutes and sometimes hours to be retrieved through most modems, which severely limited the inclusion of video and audio on web pages. The goal everyone is moving toward is streaming video or audio, which plays while the data is being received. In other words, you don’t have to completely download the clip before you can start to watch it or listen to it.

Streaming playback is now widely supported through most media players, in both standalone versions and plug-ins. When you embed a media object using the <video> element, you have fine-grained control over the buffering and playback of your multimedia resource, and the underlying media player automatically streams the media clip if the player supports streaming.

For live streaming, most modern browsers support the Media Source Extensions (MSE) specification (www.w3.org/TR/media-source/). This extends the <audio> and <video> elements to let you dynamically change the source files without using plug-ins. This allows for live streaming, splicing, and video editing right from the web page.

Workshop

The Workshop contains quiz questions and exercises to help you solidify your understanding of the material covered.

Quiz

1. How would you give a web page a black background and make all text bright green? Based on what you’ve learned in this lesson, would you even want to use that color combination?

2. What CSS properties and values would you use to ensure that a paragraph has a white background, orange text, and a 3-pixel-wide dashed green border?

3. If you have a square image of a blue flower on a transparent background, and the background color of the containing element is gray, will your flower image appear on the page as a square or as some other shape?

4. If you have an image called myimage.png and you want to align it so that a line of text lines up at the middle of the image, what style property should you use?

5. What’s the simplest method to provide access to a video on your website for the widest possible audience?

6. What is the CSS to create a background that is red with 50% transparency?

7. What is a rule for cropping an image effectively?

8. What is the most important aspect of an image for web pages: the dimensions, the file size, the colors, or the content?

9. What are two ways to align images vertically?

10. What element do you use to define a file to play in a <video> tag?

Note

Just a reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.informit.com/register and register this book (using ISBN 9780672338083), you can receive free access to an online Web Edition that not only contains the complete text of this book but also features an interactive version of this quiz.

Answers

1. Although it is highly recommended that you don’t do it, you would put the following at the beginning of the web page or use a style rule for the body element:

<body style="background-color:#000000; color:#00FF00">

2. The following properties and values would work:

background-color: #ffffff;
color: #ffa500;
border: 3px dashed #00ff00;

3. It will appear as the shape of the flower because the image has a transparent background. The gray background of the containing element will show through.

4. You can use vertical-align:middle to ensure that the text lines up at the middle of the image.

5. Just link to it:

<a href="myvideo.mov">my video</a>

6. The background-color: rgba(255, 0, 0, 0.5); property uses RGBa to define the red color with 50% alpha transparency.

7. You can apply cropping rules such as the rule of thirds, the golden ratio, the golden spiral, triangle, and diagonal crops.

8. The most important aspect of a web page image is the file size: You want it to download as quickly as possible without sacrificing quality.

9. You can align images vertically to the text top, text bottom, middle, baseline, top, and bottom.

10. You use the <source> element to define the file to play. You can also use the src attribute on the <video> tag itself.

Exercises

  • Image Select a base color that you like—perhaps a lovely blue or an earthy tone—and use the Color Scheme Designer at http://paletton.com to come up with a set of colors that you can use in a website. I recommend the tetrad or accented analogic scheme types.

  • Image When you have a set of colors—or a few options for sets of colors—create a basic HTML page with an <h1> element, a paragraph of text, and perhaps some list items. Use the color-related styles you learned about in this lesson to change the background color of the page and the text of the various block-level elements to see how these sets of colors might work together. See how they interact and determine which colors are best used for containers and which are best used for plain text, header text, and link text.

  • Image Practicing any of the image placement methods in this lesson will go a long way toward helping you determine the role that images can, and will, play in the websites you design. Using a few sample images, practice using the float style to place images and text in relationship to one another. Remember that the possible values for float are left, right, and none (default).

  • Image Find some freely available audio and video clips on the web and practice placement within your text by using the HTML5 <audio> and <video> elements.

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

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