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.
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).
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).
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.
Chances are that of all the types of media, you’ll work with images the most, so that’s a fantastic starting point.
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).
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>
.
<img>
tagFor 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).
To add an image to a webpage:
Type <img
to open the image embed tag.
Type src=
followed by the path to the image. In this example, type "space.jpg
".
Add the alt
and title
attributes. Type alt="A view of the Andromeda Galaxy" title="A view of the Andromeda Galaxy"
.
Close the img
tag by typing />
.
Save the file and open it in your browser to see the result (Figure 7.2).
<figure>
tagIf 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:
Type <figure>
to open the figure
element.
Add the image from earlier, without the title
attribute. Type <img src="space.jpg" alt="A view of the Andromeda Galaxy." />
.
Type <figcaption>A view of the Andromeda Galaxy.</figcaption>
to add a caption to the image.
Type </figure>
to close the figure
element.
Save the file and open it in your browser (FIGURE 7.5).
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
:
Create three sizes for your image: 1024, 800, and 600 pixels wide.
See Video 7.5 to learn how, if you need to.
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.
In your HTML document, type <img srcset="
.
On the next line, type space-original.jpg 6200w,
.
Press Return or Enter, then type space-1024.jpg 1024w,
.
Press Return or Enter, then type space-800.jpg 800w,
.
Press Return or Enter, then type space-600.jpg 600w"
.
We also need a fallback for older browsers that don’t support srcset
. Type src="space-1024.jpg"
.
Type />
to close the image tag.
<picture>
ElementIf 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:
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.
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.
In your HTML document, type <picture>
.
On a new line, type <source
.
Type media="(min-width: 1025px)"
.
This is the media query. It says, “If the browser has a minimum width of 1025px, use this image.”
Type srcset="space-original.jpg">
.
On a new line, type <source media="(min-width: 801px)" srcset="space-1024.jpg">
.
On a new line, type <source media="(min-width: 601px)" srcset="space-800.jpg">
.
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.
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.
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 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.
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):
<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.
To use SVG to draw a square:
Here, you’ll make a blue square.
Type <svg id="square">
.
The id
can be anything. I used square
to clearly describe what is being drawn.
On the next line, type <rect
.
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.
Type width="100" height="100"
.
This sets the dimensions of the square.
Type fill="blue"
.
This defines the color of the fill.
Close the rect
element by typing />
.
Close the SVG by typing </svg>
.
See the resulting image in FIGURE 7.10.
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.
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.
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).
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:
Type <video
.
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.
Type controls>
.
Type <source src="moon.mp4"
.
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.
Type </video>
.
The final result is what you see in Figure 7.11.
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:
Type <audio
.
Type controls>
.
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.
Type <source src="small-step.mp3" type="audio/mp3">
.
Type </audio>
.
The result will display a simple audio player in the page (FIGURE 7.12).
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).
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).
Any of these services will save you time and bandwidth (and probably a little strife too).
To embed a YouTube video on your site:
Go to YouTube.com and find a video you’d like to embed.
Click the Share button () to open the Share dialog (FIGURE 7.16).
Click Embed. The Embed Video dialog opens (FIGURE 7.17).
Copy the code in the top half of the dialog (it starts with <iframe
and ends with </iframe)
.
Open your HTML file.
Paste the embed code you just copied into the HTML file after the opening <body>
tag, and save the file (FIGURE 7.18).
Open the HTML file in a web browser.
You should see your YouTube video appear on a webpage as shown in FIGURE 7.19.
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?