Working with Images in HTML - Adding Links, Images, and Other Media - Beginning HTML5 & CSS3 For Dummies® (2013)

Beginning HTML5 & CSS3 For Dummies® (2013)

Part III

Adding Links, Images, and Other Media

9

Working with Images in HTML

In This Chapter

arrow Determining the right format for your images

arrow Adding images to web pages

arrow Creating images and image maps that trigger links

Web-page designers use images to deliver important information, direct site navigation, and contribute to overall look and feel on a web page. However, you have to use images properly, or you risk reducing their effectiveness.

This chapter is a crash course in using images on web pages. You find out which image formats are web-friendly and how to use HTML elements to add images to your web pages. You also discover how to attach links to an image and how to create image maps for a web page.

The Role of Images in a Web Page

Images in websites may be logos or clickable navigation aids, or they may display content; they can also make a page look prettier or serve to unify or illustrate a page's theme. A perfect example of the many different ways images can enhance and contribute to web pages is the White House home page at www.whitehouse.gov, shown in Figure 9-1, where the White House logo, photos, and a nice menu bar appear to good effect.

remember_4c.epsWhen used well, images are a key element of page design. When used poorly, though, they can make a page unreadable, unintelligible, or frustrating.

9781118657201-fg0901

Figure 9-1: The White House web page uses images in a variety of ways.

Creating Web-Friendly Images

You can create and save graphics in many ways, but only a few formats are actually appropriate for images you intend to use on the web. As you create web-friendly images, you must pay attention to file formats and sizes.

Often, graphics file formats are specific to operating systems or software applications. Because you can’t predict what a visitor’s computer and software will be (other than he or she will use some sort of web browser), you need images that anyone can view with any browser. This means you need to use cross-platform file formats that users can view with any version of Microsoft Windows, the Mac OS, or Linux.

These three compressed graphics formats are best for general use on the web:

check Graphics Interchange Format (GIF): Images saved as GIFs often are smaller than those saved in other file formats. GIF supports up to 256 colors only, so if you try to save an image created with millions of colors as a GIF, you lose image quality. GIF is the best format for less-complex, non-photographic images, such as line art, clip art, or icons.

check Joint Photographic Experts Group (JPEG): The JPEG file format supports 24-bit color (millions of colors) and complex images, such as photographs. JPEG is cross-platform and application-independent. A good image editing tool can help you tweak the compression so you can strike an optimum balance between the image’s quality and its file size.

check Portable Network Graphics (PNG): PNG is the latest cross-platform and application-independent image file format. It was created to combine the best aspects of GIF and JPEG. PNG has the same compression as GIF but supports 24-bit color (and even 32-bit color) like JPEG does.

Any good graphics editing tool, such as those mentioned in Chapter 23, lets you save images in any of these formats. Experiment with them to see how converting a graphic from one format to another changes its appearance and file size. Then choose whichever format produces the best results.

Table 9-1 shows guidelines for choosing a file format for images by type.

Table 9-1 Choosing the Right File Format for an Image

File Format

Best Used For

Watch Out

GIF

Line art, icons, and images with few colors and less detail

Don’t use this format if you have a complex image or photo.

JPEG

Photos or images with millions of colors and lots of detail

Don’t use with line art. Compromises quality when you compress the file.

PNG

Photos or images with millions of colors and lots of detail

Don’t use with line art. Offers best balance between quality and file size.

tip_4c.epsEach of the following sites offers a complete overview of graphics formats:

check W3C's "Graphics on the Web" article at www.w3.org/Graphics

check Quackit.com's Web Graphics Tutorial at www.quackit.com/web_graphics/tutorial

As you ponder your page design, consider this: General graphics effects such as colored or image-based backgrounds, gradients, buttons, and so forth may not require graphics at all. Before you leap to the conclusion that what your page needs is graphics, graphics, and more graphics, consult Chapters 15 and 16. Chapter 15 tackles buttons, boxes, and borders, and Chapter 16 covers use of color and backgrounds, all from a CSS perspective. You may not need as many graphics as you thought, and if you use CSS for such things, your pages will load faster, and your users will thank you for it. This goes double or triple for users on smartphones or tablets where lots of graphics could drive them to distraction (or to leave your site for good).


Optimizing images

As you build graphics for your web page, maintain a healthy balance between file quality and file size. If you poke around with your favorite search engine, you can find good tutorials on trimming image file sizes and optimizing entire sites for fast download. For tips and tricks to help you build pages that download quickly, review these handy resources:

check Optimizing images:

www.yourhtmlsource.com/optimisation/imageoptimisation.html

check Optimizing web graphics:

www.websiteoptimization.com/speed/12


Adding an Image to a Web Page

When an image is ready for the web, you need to use the correct markup to add it to your page, but you also need to know where to store your image.

Image location

You can store images for your website in several places. Image storage works best if it uses relative URLs stored somewhere on the website with your other HTML files. You can store images in the same root as your HTML files, which gets confusing if you have a lot of files, or you can create a graphics or images directory in the root file for your website.

remember_4c.epsRelative links connect resources from the same website. You use absolute links between resources on two different websites. Turn to Chapter 8 for a complete discussion of the differences between relative and absolute links.

Here are three compelling reasons to store images on your own site:

check Control: When images reside on your site, you have complete control over them. You know your images aren’t going to disappear or change, and you can work to optimize them.

check Speed: If you link to images on another site, you never know when that site may go down or respond unbelievably slowly. Linking to images on someone else’s site also causes the other site’s owner to pay for bandwidth required to display it on your pages — on another site!

check Copyright: If you show images from another site on your pages, you may violate copyright laws. If you must do this, obtain permission from the copyright holder to store and display images on your website.

Using the <img> element

The image (<img>) element is an empty element (sometimes called a singleton tag) that enables you to specify the place on the page where you want your image to go.

remember_4c.epsAn empty element uses only one tag, with neither a distinct opening nor a distinct closing tag.

The following markup places an image named 07fg02-cd.jpg, which is saved in the same directory as the (X)HTML file, between two paragraphs:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Optical Disks at Work</title>

</head>

<body>

<h1>CD/DVD as a Storage Medium</h1>

<p>CD-ROMs and DVDs have become a standard storage option in today's computing

world because they are inexpensive and easy to use.</p>

<img src="09fg02-cd.jpg" alt="line drawing of optical disk">

<p>To read from a CD or DVD, you only need a standard CD-ROM drive, but to

create CDs or DVDs, you need a DVD burner (all DVD burners can read

and write CDs as well).</p>

</body>

</html>

A web browser replaces the img element with the image file provided as the value for the src attribute, as shown in Figure 9-2.

The src attribute is like the href attribute that you use with an anchor (<a>) element. The src attribute specifies the location for the image you want to display on your page. The preceding example points to an image file in the same folder as the HTML file referencing it.

Adding alternative and title text

Alternative text describes an image so those users who can’t see the images for some reason can access that text to find out more about the image. Adding alternative text (often referred to by developers as “alt text”) is a good practice because it accounts for the following types of users:

check Visually impaired users who may not be able to see images and must rely on alternative text for a text-to-speech reader to read to them

check Users who access the website from a phone browser with limited graphics capabilities

check Users with slow Internet connections who choose not to display images

9781118657201-fg0902

Figure 9-2: Use the <img> element to place graphics in a web page.

technicalstuff_4c.epsSome search engines and cataloging tools use alternative text to index images.

Most of your users will see your images, but be prepared for those who won't. The HTML specifications require that you provide alternative text to describe each image on a web page. Use the alt attribute with the img element to add this information to your markup, like so:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Inside the Orchestra</title>

</head>

<body>

<p>Among the different sections of the orchestra you will find:</p>

<p><img src="09fg03-violin.jpg" alt="violin" title="violin"> Strings</p>

<p><img src="09fg03-trumpet.jpg" alt="trumpet" title="trumpet"> Brass</p>

<p><img src="09fg03-woodwinds.jpg" alt="clarinet and saxophone"

title="clarinet and saxophone"> Woodwinds</p>

</body>

</html>

When browsers don’t display an image (or can’t, as with text-only browsers such as Lynx), they display alternative text instead, as shown in Figure 9-3. (We turned images off in Internet Explorer because Chrome didn’t cooperate.)

9781118657201-fg0903

Figure 9-3: When a browser doesn’t show an image, it shows alternative text.

When browsers show an image, browsers — including Internet Explorer, Firefox, Chrome, Safari, and Opera — show title text as pop-up tips when you hover your mouse pointer over an image for a few seconds, as shown in Figure 9-4. This requires adding a title attribute to each <img>element, which is why it's also included in the preceding markup. Note: alt text is required for a page to validate, but title text is not required.

9781118657201-fg0904

Figure 9-4: A browser displays title text as a pop-up tip.

This means you can use alternative text to describe the image to those who can’t see it and/or title text to provide useful (or amusing) information about the same image.

tip_4c.epsThe W3C’s Web Accessibility Initiative (WAI) includes helpful tips for creating useful and usable alternatives to visual content at this site:

www.w3.org/TR/WCAG10-TECHS/#gl-provide-equivalents

warning_4c.epsYou may see suggestions to use alt text for so-called keyword stuffing from presumptive SEO experts. Search engines look for certain words in web pages and may sometimes use them to rank certain pages higher in their search results. Thus, some people take this to mean that using keywords in alt text improves page rankings. This is bogus. All we have to say is, “Don’t do it!”

Specifying image size

Use the height and width attributes with the <img> element to let the browser know just how tall and wide an image is (the default unit is pixels, or px):

<p><img src="07fg03-trumpet.jpg"

width="50" height="70" alt="trumpet" />Brass</p>

Most browsers download the HTML and text associated with a page before they download the page graphics. Instead of making users wait for the whole page to download, browsers typically display the text first and then fill in graphics as they become available. If you tell the browser how big a graphic is, the browser can reserve a spot for it in the page display. This speeds the process of populating graphics — and other stuff — on the web page.

tip_4c.epsYou can check the width and height of an image in pixels in any image editing program or in the image viewers built into Windows and the Mac OS. (You may be able simply to view the properties of the image in either Windows or the Mac OS to see its height and width.)

Another good use of the height and width attributes is to create colored lines on a page by using just a small colored square. For example, this markup adds a 10-x-10-px blue box to a web page:

<img src="09fg05-blue-box.gif" alt="blue box" height="10" width="10">

Use the <img> element height and width attributes to set image height and width. Thus we use these values to create a 10-x-10-px blue box in a browser window (shown at the top of Figure 9-5) even though the original image is 600 x 600 pixels. In general, it's safe to reduce image dimensions using these attributes although you'll always want to check the results carefully during testing. With any kind of aspect sensitive image, you want to maintain its aspect ratio by dividing the original dimensions by some common value.

9781118657201-fg0905

Figure 9-5: A series of small blue boxes.

Figure 9-5 also shows boxes with dimensions of 20 x 20 and 50 x 50 px. Here are the changes to the values for height and width in the markup to produce the other two boxes:

<img src="09fg05-blue-box.gif" alt="blue box" height="20" width="20">

<img src="09fg05-blue-box.gif" alt="blue box" height="50" width="50">

tip_4c.epsUsing this technique, you can turn a single image like the blue box (only 2.39K in size) into a variety of lines and even boxes:

check This technique can ensure that all dividers and other border elements on your page use the same color because they’re all based on the same graphic.

check If you decide you want to change all your blue lines to green, you just change the image. Every line you created changes colors.

warning_4c.epsWhen you specify an image’s height and width that are different from the image’s actual height and width, you rely on the browser to scale the image display. This trick works great for single-color images (such as the blue box), but it doesn’t work well for images with multiple colors or images that contain actual photos. The browser doesn’t size images well, and you wind up with a distorted picture. Figure 9-6 shows how badly a browser handles enlarging a trumpet image when the markup multiplies the image height by four and its width by two (note the resemblance to a flugelhorn!):

<p><img src="09fg03-trumpet" width="200" height="124" alt="trumpet"

Title = "trumpet" />Brass</p>

9781118657201-fg0906

Figure 9-6: Don’t use a browser to resize complex images; use a graphics editor!

tip_4c.epsIf you need several sizes for the same image — as for a logo or navigation button — use a large image as the master for that graphic and make smaller versions. This trick gives you better control over the final look and feel of each image.

Image borders and alignment

You must use CSS to control image borders, positioning, alignment, spacing, text flow, and more. We cover those details in Chapters 14 and 15. In case we haven’t made this sufficiently clear already, we strongly urge you to use CSS for borders, positioning, and alignment for both text and images, and let HTML do the job it does best: representing and pointing to actual content.

Images That Link

Web pages often use images for navigation. They’re prettier than plain-text links, and you can add both form and function on your page with one element.

Triggering links

To create an image that triggers a link, you substitute an <img /> element in place of text to which you would anchor your link. This markup links text:

<p><a href="http://www.w3.org">Visit the W3C</a></p>

This markup replaces the text Visit the W3C with an appropriate icon:

<p><a href="http://www.w3.org"><img src="w3.jpg"

alt="Visit the W3C Web Site"

title = "Visit the W3C Web Site" height="75" width="131"

style="border: solid blue; padding: 0.1em; margin: 2.0em;"></a></p>

The preceding markup creates a linked image to http://www.w3.org. In the preceding example, the alternative text now reads Visit the W3C Web Site, so users who can't see the image know where the link goes. When a user moves the mouse pointer over the image, the cursor changes from an arrow into a pointing hand (or any icon the browser uses for a link).

We include a blue border around this image as a visual cue to let users know it serves as a link. The border appears as a blue outline (shown in Figure 9-7).

9781118657201-fg0907

Figure 9-7: Combine image and anchor elements to create a linked image.

A quick click of the image launches the W3C website. It’s as simple as that.

tip_4c.epsYou can set the border of any image you use in a link to 0 if you want to keep the browser from surrounding your image with a blue line. Without that line, however, users need other visual (or alternative text) clues so they know that an image is a link. Be sure images that serve as links scream to the user (tastefully of course), "I'm a link!" In all cases, if the automatic outline is eliminated, you should build an outline into the graphic itself or add a caption that indicates that the image serves as a link.

Building image maps

When you use an <img> element with an anchor element to create a linking image, you can attach only one link to that image. To create a larger image that connects links to different regions on the page, you need an image map.

To create an image map, you need two things:

check An image with distinct areas obvious to users

For example, an image of a park might show a playground, a picnic area, and a pond area.

check Markup to map the different regions on the map to different URLs

Elements and attributes

Use the <img> element to add the map image into your page, just as you would any other image. In addition, include the usemap attribute to let the browser know that image map information should go with that image. The value of the usemap attribute is the name of your map.

You use two elements and a collection of attributes to define the image map:

check map holds the map information. The map element uses the name attribute to identify the map. The value of name should match the value of usemap in the <img> element that goes with the map.

check area links specific parts of the map to URLs. The area element takes these attributes to define the specifics for each section of the map:

• shape: Specifies the shape of the region (a clickable hot spot that makes the image map work). You can choose from rect (rectangle), circle, and poly (a triangle or polygon).

• coords: Defines the region's coordinates.

A rectangle’s coordinates include the left, right, top, and bottom points.

A circle’s coordinates include the x and y coordinates for the center of the circle as well as the circle’s radius.

A polygon’s coordinates are a collection of x and y coordinates for every vertex in the polygon.

tip_4c.epsTo determine image coordinates, you can use an image map editor such as Mapedit from www.boutell.com/mapedit or a graphics editor such as PaintShop Photo Pro from www.corel.com. Mapedit also records those coordinates for you.

• href: Specifies the URL to which the region links (can be absolute or relative).

• alt: Provides alternative text for the image region.

Markup

The following defines a three-region map called NavMap linked to the graphics file named 09fg08-navmap.gif:

<img src="09fg08-navmap.gif" width="302" height="30" usemap="#NavMap"

style="border: 0px; border: 2.0em;">

<map name="NavMap">

<area shape="rect" coords="0,0,99,30" href="home.html" alt="Home"

title="Home">

<area shape="rect" coords="102,0,202,30" href="about.html" alt="About"

title="About">

<area shape="rect" coords="202,0,301,30" href="products.html"

alt="Products" title="Products">

</map>

Figure 9-8 shows how a browser displays this markup.

When the mouse sits over a region in the map, the cursor turns into a pointing hand (just as it changes over any other hyperlink). So take advantage of the title text to include useful information about the link and to make the map more accessible to the visually impaired.

9781118657201-fg0908

Figure 9-8: Image maps turn different areas of an image into linking regions.

ontheweb_4c.epsA common use for image maps is to turn maps of places (states, countries, and such) into linkable maps. Here are some online resources you can use:

check The About.com image map tutorial at

http://webdesign.about.com/od/imagemaps/a/aabg051899a.htm

provides more details on building image maps by hand.

check HTMLGoodies has a great collection of image map tutorials and information at

www.htmlgoodies.com/tutorials/image_maps/index.php

check For a more fully fleshed HTML file that implements the preceding image map example, see this book’s website at

www.dummieshtml.com/html5cafe/ch09/09fig08.html

Creating image maps by hand can be tricky. Use an image editor to identify each point in your map and then create the proper markup for it. Most HTML tools include utilities to help you make image maps. If you take advantage of such a tool, you can create image maps quickly and with few errors. Find out more about HTML tools in Chapter 23.

warning_4c.epsExercise caution when using image maps. If you’re creating a visual aid (something like a map with links to different countries shown therein, for example), using an image map makes perfect sense. On the other hand, you should never use a graphic with image maps for your main navigation. (Well, you could, but you wouldn’t like the results!) Always use HTML and CSS for the main website navigation, or if you must use a graphical image map, include a text-based alternative along with that map so that visually impaired site visitors can also navigate by using the alternative controls instead.

In general, the best thing for navigation is to use text for button labels and to let CSS handle the work involved in making buttons look good. Chapter 15 discusses some truly great techniques to make text buttons pop