Adding Images with HTML

An image can be added to a Web page in two main ways. It can be embedded in the current page, or a link that points to its location can be provided. In the latter case, the image is usually displayed in a page by itself. Irrespective of whether an image is embedded or linked to, it can be used as an image map. This is an image that contains hotspots (clickable areas), which when clicked result in an event occurring, such as taking the user to a different destination to provide more information. Linking to an image is achieved using the <a> element, introduced in Chapter 4, and embedding one is achieved using the <img> element.

Traditionally, only one image source could be specified using the element, but by combining it with newer elements, such as <source> and <picture>, and with newer attributes, such as srcset and sizes, it is now possible to specify multiple image sources, from which the browser can choose the one that is best suited for a user situation, depending on the user’s device screen pixel density, zoom level, and, possibly, other factors, such as network properties. If-conditions, known as media conditions, can also be used to help the browser determine which images to use and when to use them, as

explained later. Multiple images that are provided to the browser to choose from are generally termed responsive images, and the technique is a response to the need to have images that are compatible with responsive Web design, discussed later in Chapter 21. Table 6.1 lists the main elements used for embedding an image in a page, including those used to embed an image map.

1. <img>, <source>, and <picture>

The <img>, <source>, and <picture> elements can be combined in different ways and used with various combinations of attributes to specify either a single image source or multiple image sources. The typically used attributes and their functions are listed in Table 6.2.

TABLE 6.2

Attributes Used with Elements Used to Embed Image

1.1. Specifying a Single Image Source

Although responsive image technique is the future in Web design, if a page is not required to adjust to suit different user situations, then just specifying a single image source is adequate. Also, if a page is required to adjust but the images being used are vector-based images, such as Scalable Vector Graphics (SVG), a single source can be used. This is because vector-based images can scale to different sizes, as necessary, without depreciation in quality or a change in file size. A single image source can be specified using just the <img> element and the src attribute. Figure 6.1 shows how this is done and the use of other relevant attributes. Figure 6.2 shows the result.

In the example, the src attribute specifies the image to embed (which is “yacht.jpg”) and says that it is inside a folder named “images” that is inside the folder containing the HTML document. The alt and longdesc attributes perform the functions described in Table 6.2. Using the alt attribute also contributes to accessibility, because the text is what screen readers and other assistive technologies read out to visually impaired users. For this reason, it is important for alternative text to be an accurate but concise description of the content of the relevant image. It should not be a list of keywords (known as “keyword stuffing”) designed to trick search engines, as this could get your website blacklisted (i.e., blocked by search engines). For image used only for decoration, no description is required, but the attribute should still be specified with nothing between the quotes (thus: alt=“ “).

The title attribute, which is a global attribute, provides additional description for the image and is usually displayed when cursor hovers over an image, as shown in the rendered example. However, the attribute should not be used for essential information, since you cannot rely on everyone having access to it, because not every user uses a mouse and some browsers may not display it.

The width and height attributes specify the rendered size of the image. Rendered image size can also be specified using CSS. Both approaches have advantages and disadvantages. Most importantly, specifying size by using attributes enables faster download and more orderly rendering of a page. It also prevents layout from having to be reflowed multiple times as the page loads. This is because text usually downloads faster than images and the browser by default does not know the size of an image. The result of this is that when the attributes are not used, text finishes downloading, the browser displays it, and then moves it around to fit in the image when the image finishes downloading, resulting in an untidy rendering process. In contrast, when the width and height attributes are specified and the browser encounters them, it reserves the right amount of space for the image and displays the text accordingly, so that when the image finishes downloading, it fits it in, without having to move the text significantly around. On the other hand, specifying size by using CSS (discussed in Chapter 15) allows for size to be controlled dynamically and also overrides whatever size is specified, using the width and height attributes.

1.2. Making an Image a Link, and Linking to an Image

Making an image clickable is an essential Web design practice and is done using the <a> element, which is the same element used to turn text into a hyperlink. The element and how the href attribute is used on it to create a link were discussed in Chapter 4. Figure 6.3 shows how this is done, and Figure 6.4 depicts the result.

In the example, notice that the entire <img> element, including all its attributes, is placed between the tags of the <a> element, just as is done to create text links. Also, notice that the cursor has changed shape to indicate that the image is clickable. Incidentally, the type of cursor shape to display can be specified using CSS. How this is done is shown in Chapter 17. The text link under the image links to the same image but displays it in a separate window when clicked. The first <br> element is used to place the link on a separate line, and the second to create an extra line. This is necessary, since <img> and <a> are inline elements and do not start on a new line.

1.3. Containing and Captioning Images Properly

Traditionally, the <img> element would be placed in the <p> or <div> element in order to be able to treat it as a self-contained unit. However, these elements are not semantically related to images. The <figure > container element, introduced in Chapter 2, was designed to address this. It allows images or a combination of media elements to be contained and treated as a separate unit. The <figcaption> element is intended to be used to add caption to the container. Figure 6.5 shows how the elements are used, and Figure 6.6 depicts the result.

1.4. Specifying Multiple Image Sources

In order to specify multiple image sources (i.e., responsive images), the <picture> and <source> elements need to be used with the <img> element, together with various combinations of the srcset, sizes, media, and type attributes. Situations in which it is necessary to use responsive images are known as use cases. More than one situation can occur together, in which case each situation is addressed. The commonly recognized use cases and how to specify responsive images for them are discussed here.

1.4.1. Specifying for Different Device Pixel Ratios

A device display screen is made up of many tiny dots called pixels. Device pixel ratio is the ratio of the number of these physical screen pixels to a CSS pixel, while CSS pixels are pixels used to specify lengths of elements in CSS. The difference between the two pixel types is that the size of a device pixel is typically fixed, while that of a CSS pixel is variable and can be smaller or larger than a device pixel. For example, if an image that has a width of 200 px is zoomed in, it takes up more device pixels; however, the number of CSS pixels remains the same (i.e., 200) and the CSS pixels only expand as necessary.

High-resolution screens usually contain multiple device pixels per CSS pixel. Device screen pixels are explained further later in the chapter. Providing multiple images based on device pixel ratio is sometimes called resolution switching and is necessary in situations where different users might have different technology-based circumstances. For example:

  • Users’ devices might have different physical screen sizes, usually measured diagonally.
  • Users might have screens with different pixel densities (i.e., pixels per inch).
  • Different zoom levels might be used.
  • Screen orientation might be different (e.g., landscape and portrait).
  • Network conditions (e.g., speed) might be different. This helps prevent the download of unnecessarily large images for slow systems.

To specify multiple images to deal with the above situations, the <img> element is used with the src and srcset attributes, along with the x descriptor. Figure 6.7 shows how this is done.

In the example, the browser selects any of the image sources specified in the src- set attribute, using the specified pixel density descriptors (1.5x and 2x), also known as display density descriptors. Essentially, on displays with 1.5 device pixels per CSS pixel, the image with 1.5x pixel density is used, and on those with 2 device pixels per CSS pixel, the image with 2x pixel density is used. This means that browsers on devices with high-PPI (pixels per inch) screens select a high-resolution image (i.e., one with 1.5x or 2x) and other browsers select a normal (lx) image. Where no x descriptor is specified, it is assumed to be lx. If a browser does not support the srcset attribute, it uses the image source specified in the src attribute as fallback. Newer browsers that support srcset attribute usually use the source as one of the options and use it as if specified with a lx descriptor. How x descriptors work in relation to image dimensions is that if the normal-resolution image is 400 x 268 and lx, then the image specified with 1.5x should be 600 x 402 and the image with 2x should be 800 x 536. Notice that the naming of the image files matches the x descriptors’ values. This is only good practice to avoid confusion and does not affect anything.

1.4.2. Specifying for Different Viewport Sizes

Providing multiple images for different viewport sizes is necessary in situations where different users might have devices that have different viewport widths. For example, a banner might be required to span the width of the viewport, whatever the size of the viewport, or an image might need to be sized to fit the width of differently sized columns. To specify responsive images to deal with these situations, the <img> element is used with the src, srcset, and sizes attributes, together with the w (width) descriptor. Figure 6.8 shows how this is done.

In the example, the sizes attribute specifies that image should take up 100% of the width of the viewport. The srcset attribute provides the image sources from which to choose, along with their width descriptors (i.e., widths), and the src attribute specifies the fallback image when none of the options are suitable. The browser uses this information and various other factors to determine the best image source to select, and the selected image is displayed and scaled up or down to fit the full width of the viewport.

1.4.2.1 Specifying for Different Viewport Sizes Using Media Condition

Figure 6.9 shows how media condition is used to specify the viewport widths at which different images should be used. These specified widths are called image breakpoints and are different from the breakpoints for responsive layouts, discussed later in Chapter 21.

In the example, the sizes attribute specifies that if the browser window’s width is 480 CSS pixels or less to make image take up 100% of the viewport width; if it is not, but is 800 CSS pixels or less, to make image take up 70%; and if it is neither of the two (i.e., if it is wider than 800px), to make image take up a width equal to the value specified by the last item, which is 600px. When a media condition is true, the browser uses the associated rendered size (i.e., 100 or 70 vw) and the width descriptors in the srcset attribute to determine which image source to select. The selected image is then scaled up or down to occupy the specified percentage of the viewport. In basic terms, the code says that the wider the width of the browser, the less the percentage of it that should be taken up by the image.

1.4.3. Specifying for Different Image

Providing multiple images that have varying content is necessary in situations where different users might want to change the content or aspect ratio of an image to ensure that it is displayed in the best way, based on the size of a page or a screen. For example, the same image can be shown full size on large screens, showing everything contained in it, or it can be zoomed in and cropped on smaller screens to show only important parts. Providing multiple images for purposes such as these is known as art direction. To specify responsive images to solve such use case, the <picture> element and the <source> element, together with the media attribute, are used. Figure 6.10 shows how this can be achieved.

In the example, the browser selects the first <source> element and evaluates the condition in the media attribute. If it is true, it chooses the image source in the corresponding srcset attribute. If the condition is false, the browser goes to the next <source> element and does the same thing. If all the conditions in the <source> elements are false, the image source in the <img> element is used. This means that if the browser’s width is 720 px or more, “images/yacht-fullshot .jpg” is selected; if the width is 512 px or more, “images/yacht-midshot.jp< “ is selected; otherwise, “images/yacht-closeshot.jpg” is selected.

Notice that the dimensions of the images are not specified. They need to be specified, so that the browser can allocate space for the images before they are downloaded and so prevent multiple reflowing of layout during page rendering. To provide the dimensions, CSS properties and CSS media queries (or media conditions) are used, and how to do this is explained in Chapter 15. Also, to provide the dimensions for old browsers that do not support the <picture> element, the width and height attributes can also be used on the <img> element.

1.4.3.1. Specifying for Different Image and Device Pixel Ratios

It is possible to have situations where, in addition to solving for differences in image content, there is the need to solve for device pixel ratio. In such cases, images provided in different widths are also provided in different pixel densities. Figure 6.11 shows an example of how this is done.

The <source> element in the example says that if the browser window’s width is 1024px or wider, to use one of the image sources in the srcset attribute used on it, based on the screen pixel density and other factors the browser deems relevant. This means that the high-resolution images (i.e., those with 2x and 3x) are used for high-resolution screens and the normal-resolution images are used for standard-resolution screens. If the width of the browser window is less than 1024 px, one of the image sources specified in the <img> element is used. Again, the high-resolution images are used for high-resolution screens and the normal-resolution images are used for standard-resolution screens.

1.4.4.Specifying for Different Image File Formats

When the browsers of different users are likely to support different image file formats, it might be necessary to provide images in multiple file formats. You might, for example, want to offer a not-so-popular format that is smaller in file size and has better quality (in case a user’s browser supports it) and a more popular format that has a poorer quality. This is done using the type attribute. Figure 6.12 shows an example of how this is done.

In the example, each srcset attribute specifies an image source and the type attribute specifies its MIME type. The browser goes through each <source> element and selects the first one that specifies an image whose format it supports. If it supports none of them, it selects the format specified in the <img> element. Notice how the <figure> and <figcaption> elements are used. They have the same effect as in when specifying a single image, such as shown earlier in Figure 6.6.

2. <canvas>…</canvas>

The <canvas> element allows you to draw graphics on the fly. This enables the creation of dynamic images, such as the ones necessary in games, generation of graphs, and other images in real time. The attributes that it supports are width and height. Figure 6.13 shows how it is used. The example creates a canvas that is 150 x 150 pixels in size and has a unique identification of “oneCanvas.” The fallback statement is displayed if a browser does not support the element. Note that because the element is just a container element, it does not display anything on its own, so the code does not display anything. How it is combined with JavaScript to display images is discussed in Chapter 22.

3. <svg>…</svg>

The <svg> element makes it possible to add to a Web page a type of image known as vector image (discussed more fully later in this chapter), which is created using coordinates. The element is useful for creating basic images on the fly but requires the understanding of a different type of markup language called SVG, which is beyond the scope of this book. Figure 6.14 shows how it is placed in an HTML document, and Figure 6.15 depicts the result. In the example, the SVG <svg> element defines the image, the width and height attributes define the size, and the SVG <rect> elements define the rectangles and their sizes.

4. <map>…</map> and <area>…</area>

As mentioned earlier, the <map> and <area> elements are combined with the <img> element to create image mapping. To be able to use these elements to create image maps, they need to be combined with various attributes. Table 6.3 lists them and their functions.

Image mapping has many applications. It is especially useful for providing information about different areas represented on a geographical map that would be impractical to put on the map. Essentially, an image map enables geometric areas placed on an image to be associated with hyperlinks. Creation of an image map involves the following:

  1. Declaring and naming of map, using the <map> element with the name attribute.
  1. Creating the hotspot regions, using the <area> element with the shape and coords attributes. The coordinates of shapes are typically difficult to work out. However, there are now various tools on the Web for doing this.

A search for “image mapping” should reveal some of them. They allow an image to be uploaded and hotspots to be drawn on it, after which the x-y coordinates are generated, based on the top-left corner of the image being 0,0. Some also generate the image-map HTML code.

  1. Linking of the hotspots to the desired destinations (files), using the href attribute.
  2. Associating the map with an image containing areas and labels that correspond to the hotspots, using the usemap attribute. This, in principle, is like superimposing the hotspot shapes on the image.

Figure 6.16 gives a rough illustration of the components of an image map, and Figure 6.17 shows part of the code for implementing an image map.

In the example, the first <area> element creates a hotspot shape of the London region, which when clicked takes users to another page that provides information about the region. The second <area> element does the same for the Northeast region, and all the other regions (i.e., hotspot shapes) are created in the same way, all of which are enclosed within the <map> element. In the coords attributes, the first two numbers specify the x-y coordinates of the first point of the shape being created, and the next two numbers specify the x-y coordinates of the second point, and so on.

Source: Sklar David (2016), HTML: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

Your email address will not be published. Required fields are marked *