7

Media

You’ve learned how to add text and create semantic layouts, and that’s great! But media—images, video, and audio—is what makes websites really stand out.

Media in this case refers to any non-plain-text file. And in this chapter, you’ll learn how to embed images, videos, and audio. You’ll also learn the ins and outs of finding good resources and where to host multimedia.

How Does Media Work on the Web?

The nice thing about using media on a webpage is that all you have to do is store the media files on your web server and insert links to them into your HTML files. The browser will know how to open most common forms of media (FIGURE 7.1).

The web browser window shows an image of the Andromeda galaxy, the image occupies the entire region of the page.

Figure 7.1 An image open in a browser window

But if you use HTML tags to tell the browser the type of media you’re linking to, you can display that media directly on the page—without having to open separate windows or applications (FIGURE 7.2).

The web browser window shows an image of the Andromeda galaxy in the universe, the image is left-aligned. The text "The Andromeda Galaxy has diameter of about 220,000 light years, and contains about 1 Trillion stars. That's double our galaxy - the Milky Way!" is displayed on the top of the image.

Figure 7.2 An image embedded on a page

This is known as embedding the media file. The media can be viewed, watched, or listened to without the user leaving the page.

Thanks to features of HTML5, you can tell the browser how to handle images, video, and audio. You can embed them directly into the page, and even give some instruction on how to display or control them—play, pause, mute, rewind, and more.

Other forms of media, like Microsoft Word documents, PDFs, and presentation software slide shows, can be linked in the browser but not embedded. The browser will rely on another program on the device to handle opening the file.

Images

Chances are that of all the types of media, you’ll work with images the most, so that’s a fantastic starting point.

Types of images

There are lots of different types of image that can be stored in a variety of file formats; these formats serve different purposes. For example, the most common type of image used on webpages is photos. They are typically in JPEG format, which compresses them so that their file sizes are not gigantic. Simple animated images will be in GIF format. Lightweight graphics will often be in PNG format; they can use transparent backgrounds. And more complex graphics that need to be displayed at several different sizes are usually in scalable vector format (or SVG). You can resize SVGs without worrying that you will lose image quality.

The types of images supported in HTML are determined by the browser, and as a result, certain file types will work only in certain browsers.

The most common image types will work in all browsers: JPEG, GIF, PNG, and SVG. These images use the file name extensions .jpg, .gif, .png, and .svg, respectively (FIGURE 7.3).

The web browser window shows the image of the Andromeda galaxy. The filename of the image space.jpg at the address bar of the browser is highlighted.

Figure 7.3 This image of space is called space.jpg.

Adding Images to a Page

Once you’ve got the images you want to use in the right format, it’s time to add code to your HTML to insert the images into the page’s flow. Next, you’ll learn about two elements you can use to place an image on a page: <img> and <figure>.

The <img> tag

For all supported image types except SVG (that’s coming later), you will use the image embed tag <img>. This tag is unique because in addition to requiring an attribute (src), it has no end tag. Here’s some sample markup:

<img src="space.jpg" alt="A view
of the Andromeda Galaxy"
title="A view of the Andromeda
Galaxy" />.

All images should also include an alt attribute, whose value is text that describes the image. While this isn’t required for the tag to work, it is required to make your website accessible (for more on website accessibility, see Chapter 24).

The title attribute can also include this text. The main difference (besides semantic meaning) is that the title will appear in a tool tip when you hover over an image (FIGURE 7.4).

The image of the Andromeda galaxy in a web browser windows is shown. The title of the image "A view of the Andromeda galaxy" is displayed by hovering the cursor over it.

Figure 7.4 The image’s title showing on hover

To add an image to a webpage:

  1. Type <img to open the image embed tag.

  2. Type src= followed by the path to the image. In this example, type "space.jpg".

  3. Add the alt and title attributes. Type alt="A view of the Andromeda Galaxy" title="A view of the Andromeda Galaxy".

  4. Close the img tag by typing />.

  5. Save the file and open it in your browser to see the result (Figure 7.2).

The <figure> tag

If you want to make meaningful additions to the flow of your page, or group an image with a caption, you’ll use a figure with an optional caption element. Its tag is <figure>, and to associate a caption with it you insert the element <figcaption> inside it. The structure looks like this:

<figure>
    <img src="space.jpg" alt="A view
    of the Andromeda Galaxy" />
    <figcaption>A view of the
    Andromeda Galaxy</figcaption>
</figure>

Note these points about the use of the figure tag:

  • You can put more than one image in a <figure> tag if they make sense together in context.

  • Everything inside the opening and closing <figure> tags creates a single, self-contained unit.

  • Since figures are self-contained, you should be able to move a figure up or down on a page without changing the meaning of the page.

That last point also means that not all images are figures.

To add a figure to the page:

  1. Type <figure> to open the figure element.

  2. Add the image from earlier, without the title attribute. Type <img src="space.jpg" alt="A view of the Andromeda Galaxy." />.

  3. Type <figcaption>A view of the Andromeda Galaxy.</figcaption> to add a caption to the image.

  4. Type </figure> to close the figure element.

  5. Save the file and open it in your browser (FIGURE 7.5).

The browser window shows the photograph of the Andromeda galaxy with the caption "A view of the Andromeda galaxy."

Figure 7.5 Our photo of the Andromeda galaxy, now with a caption

Responsive Images: Considering Different Devices and Connections

One of the biggest issues with adding images to webpages is that, depending on the file size of the images, they can unnecessarily bloat the site and make it very slow to download. Here’s an example: the full size of the space image is 6200×6200, coming in at 4.2MB (4200KB).

If we resize it to 1920×1920, 30 percent of the original size, the file size is 415KB. That’s 9 percent of the original file size!

That size difference will have a considerable effect on the time it takes to download the page, and it will have little to no effect on how most visitors see the image; 1920 pixels is still overkill if you consider that most mobile screen sizes are considerably smaller.

However, you might wonder what happens if someone is viewing the page on a big monitor or even a TV, where they would rather take advantage of the full size of the screen. That’s where the srcset attribute comes in.

This attribute tells the browser that it has a range of image files to choose from when rendering the <img> element.

Here’s an example:

<img srcset="
    space-original.jpg 4x,
    space-large.jpg 3x,
    space-medium.jpg 2x,
    space-small.jpg 1x"
src="space-medium.jpg" />

Note that src is included to provide a fallback for browsers that don’t support srcset yet.

Within the srcset attribute, include a comma-separated list of different images (or the same image at different sizes). For each image, provide its path as well as a relative size value (that is, 4 times, 3 times, etc.) notated as 4x, 3x, etc. (Note that 1x is implied and not required).

These numbers represent the pixel density of the user’s browser (the number of pixels available in a chosen area of the display), and they tell the browser how to choose which image to download and serve to the user depending on the device’s pixel density. If the device has a very high pixel density, it can choose to display the 4x image. If its display has a lower resolution, it might download and display only the 2x or 1x image. This will save on load time and bandwidth.

Alternatively, you can specify the image widths in pixels instead of expecting the browser to use pixel density to decide which file to use. So you would replace 4x with 6200w (6200 pixels is the original image’s width), 3x could be replaced with 4650w, and so on. This gives the browser more information about the image, so it can replace the images while taking into account both the characteristics of the device and the image width.

To add an image using srcset:

  1. Create three sizes for your image: 1024, 800, and 600 pixels wide.

    See Video 7.5 to learn how, if you need to.

  2. Save them in the same folder as your HTML file.

    For the purposes of this task, name the images following the pattern space-[size].jpg, which gives us space-original.jpg, space-1024.jpg, and so on.

  3. In your HTML document, type <img srcset=".

  4. On the next line, type space-original.jpg 6200w,.

  5. Press Return or Enter, then type space-1024.jpg 1024w,.

  6. Press Return or Enter, then type space-800.jpg 800w,.

  7. Press Return or Enter, then type space-600.jpg 600w".

  8. We also need a fallback for older browsers that don’t support srcset. Type src="space-1024.jpg".

  9. Type /> to close the image tag.

The <picture> Element

If you want more fine-grained control of when images show up, you could use the <picture> element. It’s very similar to using srcset, but the markup is a bit different.

One thing it makes use of is media queries, which you’ll learn more about in Chapter 17. The quick explanation is that you can use CSS to get information about the browser, like screen width, and then adjust the display of your website based on that information.

To use the <picture> element to show different images:

  1. Create three sizes for your image: 1024, 800, and 600 pixels wide.

    See Video 7.5 to learn how to create these versions of your image if you need to.

  2. Save them in the same folder as your HTML file.

    For the purposes of this task, the images will be named following the pattern space-[size].jpg, which gives us space-original.jpg, space-1024.jpg, and so on.

  3. In your HTML document, type <picture>.

  4. On a new line, type <source.

  5. Type media="(min-width: 1025px)".

    This is the media query. It says, “If the browser has a minimum width of 1025px, use this image.”

  6. Type srcset="space-original.jpg">.

  7. On a new line, type <source media="(min-width: 801px)" srcset="space-1024.jpg">.

  8. On a new line, type <source media="(min-width: 601px)" srcset="space-800.jpg">.

  9. On a new line, type <img src="space-600.jpg" />.

    This serves as a fallback in two cases: for browsers that don’t support the picture and source elements, and for when every media query returns false. In this case, it’s for when the browser window has a width of 600px or smaller.

  10. Type </picture>.

Ultimately, there’s no major difference between srcset and picture, except that srcset does a bit more of the work for you; srcset is the method more commonly used today.

Using SVG

If you can use Scalable Vector Graphics (SVG), that would go a long way in saving you on file size. But SVGs may not be as straightforward to use, mostly because they have to be designed in a program like Adobe Illustrator.

SVGs are best used for illustrations or logos and can’t be used for photographs (FIGURE 7.6). These are computer-generated graphics that are more abstract than photographs, which accurately depict real life. Illustrations and logos can be described as rules more efficiently.

The browser window shows an example of Scalable Vector Graphics (SVG). The file 7.html displays an image of a rocket on the browser.

Figure 7.6 This image is a good example of an SVG.

The reason for that is the same reason they scale so well: the image data is stored not as pixels, but by mathematical instructions for drawing the image. That means that if you resize the image, the display pixels are recalculated for the resolution of the screen. So the image is sharp and crisp at any size, without pixelation. See FIGURE 7.7 for an example of the source code for Figure 7.6.

A screenshot shows a sample source code for a Scalable Vector Graphics.

Figure 7.7 A sample of source code for an SVG

Another nice thing about SVGs is that they can be treated like any other image, using the img tag. Here’s the HTML for including Figure 7.6 on a webpage:

<img src="rocket.svg" alt="my rocket
ship" />

But when you add a size to it, the graphic scales appropriately (FIGURE 7.8):

A screenshot depicts the magnified clear view of the top portion of a rocket which is an example of Scalable Vector Graphics.

Figure 7.8 What happens when you scale an SVG to over 9000px. Notice there is no pixelation.

<img src="rocket.svg" width="9001px"
alt="my rocket ship" />

You can also add an SVG directly to a webpage using the <svg> tag. Here’s what that could look like:

<svg>
  <circle cx="100" cy="100" r="50"
  fill="red" />
</svg>

The result is shown in FIGURE 7.9.

A figure presents a red circle, which is a Scalable Vector Graphics Circle in a webpage.

Figure 7.9 Embedding an SVG circle directly on a webpage

To use SVG to draw a square:

Here, you’ll make a blue square.

  1. Type <svg id="square">.

    The id can be anything. I used square to clearly describe what is being drawn.

  2. On the next line, type <rect.

  3. Type x="0" y="0".

    This tells the browser the starting coordinates of the shape. In this case, you want the shape to be in the upper-left corner of the page, so you can start at 0, 0 (as in 0 pixels to the left, and 0 pixels down). I encourage you to experiment with these numbers to see what they do.

  4. Type width="100" height="100".

    This sets the dimensions of the square.

  5. Type fill="blue".

    This defines the color of the fill.

  6. Close the rect element by typing />.

  7. Close the SVG by typing </svg>.

See the resulting image in FIGURE 7.10.

A figure shows a blue Scalable Vector Graphics Square.

Figure 7.10 Your code created this blue SVG square.

Other Media

Aside from images, you can embed videos and audio directly into a webpage. In this section, you’ll learn not only how to do that, but also the kinds of video and audio files that can be displayed by common modern web browsers. You’ll also learn about factors to consider when storing large media on your server.

Video and audio file “formats”

When web developers talk about embedding video and audio files in webpages, they generally refer to a file’s format to distinguish one kind of file from another. Yet web developers use “format” in a general sense to describe a combination of characteristics of a file, whereas video and audio professionals use the word in a stricter sense. These divergent uses of the word can lead to confusion and misunderstanding, so it’s worth taking a moment to try to sort out the issue.

What distinguishes one kind of media file from another is a complex mix of technical parameters, which can be broken down into file type, codec, and format:

File type: Also called a file container, this is the way that the video or audio data is packaged into a file that a computer can read. Anything with a file extension is a file type, like .MOV, .MP4, etc. Each of these file types can contain video or audio data stored in one of several different ways (or even other kinds of data, like image data, subtitles, etc.). These file types are often called “formats,” even though the video in one .MP4 file, for example, might be of a very different type from the video in another .MP4 file.

Codec: Recording video or audio data directly from a camera or a microphone produces truly vast amounts of digital data. To make this data more manageable, it’s almost always compressed for storage, then decompressed when it’s needed for editing or playback. The media industry uses numerous standards for this process; these are known as codecs short for “compressor/decompressor.” You can think of the codec as the “language” in which the video or audio data is stored. H.264 is a very common video codec, and MP3 is an audio codec. Confusingly, H.264 video is usually stored in a .MP4 or .MOV file, but MP3 audio is often stored in a .MP3 file. (Note that not all video in a .MP4 or .MOV file uses the H.264 codec).

Format: This refers to the internal structure of the media data. For video, this includes frame size, frame rate, and pixel aspect ratio. Features of audio formats include the number of channels and configuration of those channels (whether stereo, multiple-mono, 5.1 surround-sound, etc.).

Like most of the web world, in this book I’ll use “format” in a more general sense. When I talk about files in the MP4 format, I mean “video encoded using the H.264 codec and using MP4 as the file type.”

When you embed video or audio in your webpage, take care to choose files in formats that the most common browsers support. The best solution for video is usually to choose MP4, because all browsers support it, with some exceptions (TABLE 7.1).

Table 7.1 Video Formats

Format

Supported Browsers

MP4*

All (Internet Explorer, Firefox, Chrome, Safari, Opera)

WebM

Chrome, Firefox, Opera

Ogg

Chrome, Firefox, Opera

*Except for H.265-encoded video

If you use MP4, be sure your video is encoded with H.264. Quite a bit of video created on Apple iPhones since 2017 uses the H.265 codec (or HEVC) which is incompatible with some browsers. You might also consider either Ogg or WebM for performance or for reasons of personal preference.

As with embedding video, when you embed audio in your webpage you need to be mindful of the formats that are supported. WAV is supported by all browsers except Internet Explorer. The MP3 format is supported by all browsers (TABLE 7.2).

Table 7.2 Audio Formats

Format

Supported Browsers

MP3

All (Internet Explorer, Edge, Firefox, Chrome, Safari, Opera)

WAV

Chrome, Firefox, Safari, Opera, Edge

Ogg

Chrome, Firefox, Opera

You’ll notice that Ogg is both a video and audio format.

Embedding Video

You can embed a video on your webpage with the <video> element. There are a few attributes to know as well: width, height, and controls. The controls attribute has no value, but adding it tells the browser to include the play, pause, and volume buttons (FIGURE 7.11).

A screenshot shows a webpage with a video embedded in the page along with a video play button, screen maximize button, and a volume button. The screen shows a portion of the moon on a dark background.

Figure 7.11 This webpage has an embedded video with playback controls displayed.

Between the opening and closing <video> tags, you need to include the video source.

Luckily, you can add multiple video sources (which can use different formats), and the browser will pick the best one.

You should always include an MP4, since that is supported by all browsers.

To embed a video on a webpage:

  1. Type <video.

  2. Type width="800px".

    You can skip the height attribute since the browser will intelligently resize the video to the appropriate height based on the width.

  3. Type controls>.

  4. Type <source src="moon.mp4".

  5. Type type="video/mp4">.

    This is not completely necessary in modern browsers, but it’s still good to include, especially if you use multiple sources.

  6. Type </video>.

The final result is what you see in Figure 7.11.

Embedding Audio

Adding audio to a webpage is very similar to adding video. The HTML is formatted exactly the same, except you’ll use the <audio> tag instead of the <video> tag:

<audio controls>
    <source src="small-step.wav"
    type="audio/wav">
    <source src="small-step.mp3"
    type="audio/mp3">
</audio>

To embed audio on a webpage:

  1. Type <audio.

  2. Type controls>.

  3. Type <source src="small-step.wav" type="audio/wav">.

    As a reminder, this relative path means the WAV file is in the same directory as the HTML file.

  4. Type <source src="small-step.mp3" type="audio/mp3">.

  5. Type </audio>.

The result will display a simple audio player in the page (FIGURE 7.12).

A screenshot presents the player for an embedded audio clip. A play button, the duration of the audio clip, the audio track bar, and the volume control are displayed in the player.

Figure 7.12 This is the player for an embedded audio clip.

Storing Multimedia Files

Small files like images, SVGs, and PDFs can be stored directly on your server, in the same folder as your website. That’s because these files don’t require the user to interact with them and therefore are not resource intensive. In other words, they don’t require a lot of computing power (as would playing a video game), so they won’t cause stress on your website.

Multimedia—audio and video—will use considerable resources and bandwidth that your web server is likely not specialized for. This can lead to your website crashing or quickly running out of storage and bandwidth.

Instead, you should use specialized services to host your media, and then embed links to those services into your website using the embed code provided by the service. You can also get plain links (directly to an .mp3 or .mp4 file) and embed them using the audio or video element.

For video, many great services are available. Both YouTube (FIGURE 7.13) and Vimeo are free. If you need more in terms of features or control, Vimeo also offers paid plans (FIGURE 7.14).

A screenshot depicts the home page of YouTube. Different navigation bars are aligned along the left pane of the page. The trending video thumbnails are displayed in two rows.

Figure 7.13 YouTube provides a great service for hosting free videos.

A screenshot shows the web page of Vimeo which offers different plans for hosting videos. It presents the various plans along with the amount and the features provided in each plan. The plans mentioned are as follows: Plus, Pro, Business, and Premium.

Figure 7.14 Vimeo offers hosting plans at a variety of price points.

For hosting audio, things are a little tough. SoundCloud is a popular free option, but it comes with limitations. Podbean is a podcasting service that has a free tier, but you’re probably better off paying for a service.

Libsyn is a great audio hosting service that starts at $5 a month (FIGURE 7.15).

The web page of Libsyn with popular plans is shown.

Figure 7.15 Libsyn offers a variety of audio hosting plans.

Any of these services will save you time and bandwidth (and probably a little strife too).

To embed a YouTube video on your site:

  1. Go to YouTube.com and find a video you’d like to embed.

  2. Click the Share button (Share button) to open the Share dialog (FIGURE 7.16).

  3. Click Embed. The Embed Video dialog opens (FIGURE 7.17).

  4. Copy the code in the top half of the dialog (it starts with <iframe and ends with </iframe).

  5. Open your HTML file.

  6. Paste the embed code you just copied into the HTML file after the opening <body> tag, and save the file (FIGURE 7.18).

  7. Open the HTML file in a web browser.

    You should see your YouTube video appear on a webpage as shown in FIGURE 7.19.

A screenshot shows the YouTube share dialog box.

Figure 7.16 The YouTube share dialog

A screenshot displays a YouTube embed screen. A video is displayed which is paused. An embed video dialog box is present on the right side of the page. An embed code is present on the top portion of the dialog box.

Figure 7.17 The YouTube Embed screen with embed code

A screenshot presents the YouTube embed code in an HTML file. The YouTube embed code is copied within the body tag, which includes the frame width, height, source link, frame border, and the permission to accelerometer, autoplay, encrypted-media, gyroscope, picture-in-picture, and full screen.

Figure 7.18 The YouTube embed code in an HTML file

A screenshot shows a YouTube video on a webpage. The video is paused. The name of the video is displayed on the top left corner and the two options, watch later and share are displayed on the top right corner of the video.

Figure 7.19 A YouTube video embedded on a webpage

Wrapping Up

Phew! That was a lot to take in—but now you know how to add all sorts of media to your website. This will make it more visually appealing and interactive, and it will add something beyond just text. After all, a picture’s worth a thousand words, right?

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

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