Lesson 5 / 863%

Lesson 5

Images and media

20 min

Insert images, videos and sounds with img, video, audio.

Inserting an image

The <img> tag lets you insert an image. It has no closing tag and requires at least the src(path to the image) and alt (alternative text) attributes.

Unlike a word processor, the browser does not "embed" the image in the HTML file: it reads the tag, finds the address given in src, then downloads the image file separately. Your HTML file and your images are therefore two distinct things, and if the path is wrong, the image won't appear.

image.html
<img src="/images/cat.jpg" alt="A black cat sitting on a sofa" />

<!-- With explicit dimensions (prevents layout shifts) -->
<img
  src="/images/cat.jpg"
  alt="A black cat sitting on a sofa"
  width="400"
  height="300"
/>

Result (open in a browser)

Result in the browser: a black cat sitting on a sofa

The alt attribute is essential: it is read by screen readers for visually impaired people, it is displayed if the image fails to load, and it is taken into account by Google for image search. An empty alt="" is acceptable only for a purely decorative image.

Writing good alternative text

A good alt describes what the image contributes to the page, as if you were describing it to someone over the phone. It should not start with "image of" or "photo of": the screen reader already announces that it is an image.

Useful

<img
  src="/market.jpg"
  alt="Colorful fruit and vegetable
  stalls at the market"
/>

Useless

<img
  src="/market.jpg"
  alt="image1"
/>

<img src="/market.jpg" />

If the image is a simple decorative element (an ornamental line, a background), use alt="": the screen reader will ignore it completely. If the image contains important text (a poster, a diagram), copy that text into the alt attribute or into the neighboring paragraph.

Choosing the right image format

Not all images are equal: the format you choose greatly changes the file size, and therefore the loading speed of your page.

  • JPEG (.jpg) — ideal for photos, with compression that reduces file size at the cost of a slight loss of quality.
  • PNG (.png) — lossless and with transparency, suited to logos, screenshots and diagrams, but heavier for photos.
  • WebP (.webp) — a modern format, lighter than JPEG and PNG at equal quality, supported by all recent browsers. It is the format used for the images in this course.
  • AVIF (.avif) — even better compression, and increasingly widespread.
  • SVG (.svg) — a vector image described by code: it never loses sharpness, whatever the size. Perfect for icons and logos.
  • GIF (.gif) — allows short animations, but is very heavy; a silent looping video is often a better choice.

Image paths

The value of src follows the same rules as that of href for links: it can be an absolute path, a relative path, or a full address.

image-paths.html
<!-- Absolute path from the site root -->
<img src="/images/logo.png" alt="Site logo" />

<!-- Relative path: "images" folder next to the HTML file -->
<img src="images/logo.png" alt="Site logo" />

<!-- Image hosted elsewhere (avoid if possible) -->
<img src="https://example.com/photo.jpg" alt="External photo" />

Avoid pointing to images hosted on someone else's site: you don't have the right to use them without permission, and they can disappear overnight, leaving a hole in your page. Also think about copyright: use your own photos or royalty-free image banks.

Making an image clickable

You can wrap an image in a link, exactly like text.

image-link.html
<a href="/products/chair">
  <img src="/images/chair.jpg" alt="View the light wooden chair" />
</a>

In this case, the alt attribute acts as the link text: it should describe the destination ("View the light wooden chair") rather than the image itself.

Captioning an image with figure and figcaption

To associate an image with a caption, HTML5 offers the <figure> tag, which groups illustrative content, and <figcaption>, which is its caption. This explicitly links the image and its text, which a simple paragraph placed underneath does not do.

figure.html
<figure>
  <img
    src="/images/baobabs.jpg"
    alt="Avenue of baobabs at sunrise"
    width="600"
    height="400"
  />
  <figcaption>The Avenue of the Baobabs, near Morondava.</figcaption>
</figure>

Responsive images

To serve images of different sizes depending on the screen (mobile, tablet, desktop) and thus save bandwidth, HTML5 offers the srcset attribute.

srcset.html
<img
  src="/images/photo-800.jpg"
  srcset="
    /images/photo-400.jpg 400w,
    /images/photo-800.jpg 800w,
    /images/photo-1200.jpg 1200w
  "
  sizes="(max-width: 600px) 400px, 800px"
  alt="Mountain landscape at sunset"
/>

The browser automatically picks the best image among those offered, depending on the size of the user's screen.

Let's break down these two attributes. In srcset, each line associates a file with its actual width in pixels(the w suffix). In sizes, you indicate at what width the image will be displayed: here 400 pixels if the screen is 600 pixels wide or less, 800 pixels otherwise. With these two pieces of information, the browser picks the best-suited file, also taking the screen's pixel density into account.

Offering several formats with picture

The <picture> tag lets you offer several versions of the same image: modern formats for browsers that support them, and a classic format as a fallback. It can also be used to display a different image depending on the screen size (a mobile crop, for example).

picture.html
<picture>
  <!-- The browser takes the first source it can read -->
  <source srcset="/images/photo.avif" type="image/avif" />
  <source srcset="/images/photo.webp" type="image/webp" />

  <!-- Fallback image, required -->
  <img src="/images/photo.jpg" alt="Sunset over the beach" />
</picture>

The <img> tag inside <picture> is mandatory: it is the one that actually displays the image, and it carries the alt attribute.

Loading images at the right time

A page with lots of images can be slow to load. The loading="lazy" attribute asks the browser to download the image only when the user gets close to its position on the page, which speeds up the initial display.

lazy.html
<!-- Image at the very top of the page: loads immediately -->
<img src="/images/banner.webp" alt="Site banner" width="1200" height="400" />

<!-- Images further down the page: deferred loading -->
<img
  src="/images/gallery-1.webp"
  alt="First photo of the gallery"
  width="600"
  height="400"
  loading="lazy"
/>

Don't put loading="lazy" on the main image that is visible as soon as the page opens: it should display as quickly as possible.

Video

HTML5 lets you embed video natively, without an external plugin (goodbye Flash), thanks to the <video> tag.

video.html
<video controls width="480" poster="/images/preview.jpg">
  <source src="/videos/demo.mp4" type="video/mp4" />
  <source src="/videos/demo.webm" type="video/webm" />
  Your browser does not support video playback.
</video>
  • controls displays the browser's default play/pause/volume buttons.
  • poster defines the image displayed before playback starts.
  • Several <source> tags let you offer several formats: the browser picks the first one it can read.
  • Other useful attributes: autoplay, loop, muted (autoplay generally only works if the video is also muted).

There is also the preload attribute, which indicates what the browser may download in advance: none(nothing), metadata (only the duration and dimensions) or auto (the browser decides). For a page containing several videos, metadata avoids needlessly using up your visitors' mobile data.

Adding subtitles

A video without subtitles is inaccessible to deaf or hard-of-hearing people, and unusable for anyone watching without sound (on public transport, for example). The <track> tag lets you attach a subtitle file in WebVTT format.

video-subtitles.html
<video controls width="480">
  <source src="/videos/demo.mp4" type="video/mp4" />
  <track
    kind="subtitles"
    src="/videos/demo-en.vtt"
    srclang="en"
    label="English"
    default
  />
</video>

Audio

Same principle for sound, with the <audio> tag.

audio.html
<audio controls>
  <source src="/sounds/music.mp3" type="audio/mpeg" />
  <source src="/sounds/music.ogg" type="audio/ogg" />
  Your browser does not support audio playback.
</audio>

The controls, loop, muted and preload attributes work the same way as for video. For a podcast or a spoken recording, remember to also offer a written transcript underneath: it helps deaf people, but also everyone who prefers to read, and it is indexed by search engines.

Embedding an external video with iframe

Hosting videos yourself takes a lot of space and bandwidth. It is common to embed a video hosted on a platform (YouTube, Vimeo...) using the <iframe> tag, which displays a web page inside your own. The platform usually provides the code to copy via its "Share" and then "Embed" button.

iframe.html
<iframe
  width="560"
  height="315"
  src="https://www.youtube.com/embed/VIDEO_ID"
  title="Presentation of my project"
  loading="lazy"
  allowfullscreen
></iframe>

The title attribute is important here for accessibility: it describes the content of the iframe to screen readers. Only embed trusted sites, because the content of the iframe is managed by a third party.

Best practices

  • Always compress your images before putting them online (generally under 200-300 KB).
  • Avoid autoplay with sound: it is a bad user experience, and often blocked by browsers.
  • Always set width/height to prevent the page from "jumping" while loading.
  • Give your files clear names, without spaces or accents (for example black-cat.webp).
  • Always provide an alternative for media: alternative text, subtitles or a transcript.

Common beginner mistakes

  • Getting the src path wrong: the browser then displays the broken image icon with the alternative text.
  • Forgetting the alt attribute, or filling it with the file name (alt="IMG_2043").
  • Uploading multi-megabyte photos straight from your phone, without resizing or compressing them.
  • Using width and height with proportions different from those of the image, which distorts it.
  • Forgetting controls on a video or audio: the player stays invisible and the user can't start anything.
  • Choosing a file format that not all browsers can play, without offering a fallback source.

Key takeaways

  • img requires srcand alt; the alternative text should describe the purpose of the image
  • Choose the format according to the content: WebP or JPEG for photos, SVG for logos and icons, PNG for transparency
  • figure and figcaption caption an image; srcset and picture adapt the image to the screen and the browser
  • video and audioare controlled with attributes (controls, poster, preload...) and several source tags
  • Think about accessibility: subtitles, transcripts and alternative texts
  • Compress and size your media to keep your page fast

Exercise

Add an image to your "About me" page with relevant alternative text, then embed a video or a sound of your choice with the playback controls visible.

Going further

Make your image clickable by wrapping it in a link to an external page of your choice, then add a poster attribute to your video to define a preview image.

Challenge: a mini gallery

Create a "Gallery" page with three photos of your choice, each placed in a <figure> tag with a <figcaption> caption and carefully written alternative text. Add loading="lazy" to the last two images, then use <picture> to offer a WebP version and a JPEG version of the first one. Finish by embedding a video with an <iframe> or <video> tag, then check the total weight of your page in the developer tools (F12, "Network" tab).