Chapter 08 of 26

Images

A page of plain text works, but diagrams, photos, logos and screenshots make content far easier to understand. Imagine learning about a binary tree without ever seeing one drawn!

In this chapter, we'll learn how to add images with the <img> element, how to write good alternative text, why width and height matter for performance, which image format to pick, how to add captions, and how to load images lazily.

The <img> Element

The <img> element embeds an image in a page. It needs a src attribute (the image's URL) and an alt attribute (a text alternative for people and programs that can't see the image).

<img src="images/binary-tree.png" alt="A binary tree with root 8, left child 3 and right child 10">

Some important things to notice:

  • <img> is a void element — it has no content and no closing tag. Writing <img ... /> with a slash is also allowed, but the slash does nothing in HTML.
  • The image is not part of the HTML file. The browser makes a separate request for the file named in src and draws it in place.
  • By default, an image is an inline element: it sits on a line of text, just like a word.

The src Attribute

src follows exactly the same URL rules we learned in Links:

src valueMeaning
logo.pngFile in the same folder as the page
images/logo.pngInside the images folder
../images/logo.pngGo up one folder, then into images
https://example.com/logo.pngAbsolute URL on another site

Prefer storing images on your own site. Linking directly to images on someone else's server (called hotlinking) uses their bandwidth, may be against their terms, and breaks if they move the file.


Alternative Text: The alt Attribute

The alt attribute is the most important part of an image that nobody sees. Its text is used when:

  • a screen reader reads the page to a blind or low-vision user;
  • the image fails to load (slow network, wrong path, blocked file);
  • a search engine tries to understand what the image shows.

The HTML standard requires an alt on every image (with a few rare exceptions). But what you write depends on the image's role.

1. Informative Images

The image adds information. Describe that information briefly — usually one sentence.

<img src="images/osi-model.png" alt="The seven OSI layers, from Physical at the bottom to Application at the top">

2. Decorative Images

The image is pure decoration (a divider line, a background flourish). Use an empty alt, alt="". This tells screen readers to skip the image completely.

<img src="images/divider.png" alt="">

Empty alt is not the same as missing alt. If alt is missing entirely, many screen readers read out the file name instead — imagine hearing “IMG underscore 2 0 2 6 1 0 dot J P G”.

3. Functional Images

The image is inside a link or button. Describe the action or destination, not the picture.

<a href="index.html"><img src="images/logo.png" alt="CS Learning Portal home"></a>

4. Images of Text

If an image contains text (like a poster), the alt should contain that text. Better still, avoid images of text and use real HTML text, which can be resized, translated and searched.

Writing Good Alt Text

Bad altWhy it's badBetter alt
alt="image"Says nothingalt="Graph of n² growing faster than n log n"
alt="image of a stack"“Image of” is redundant — screen readers already say it's an imagealt="A stack with 5 on top of 3 on top of 1"
alt="IMG_2026.jpg"File names aren't descriptionsalt="Students in the computer lab"
No alt on a decorative imageFile name may be read outalt=""

A useful test: if you described this page over the phone, what would you say about the image? That's your alt text. If you wouldn't mention it at all, use alt="".


Width and Height

<img src="images/campus.jpg" alt="College main building" width="800" height="500">

width and height give the image's dimensions in CSS pixels. They are plain integers — no units. Writing width="800px" is invalid.

Why Set Them? Layout Shift.

Here's what happens when a page loads without image dimensions:

Time 0 ms     Text loads. Image size is unknown, so it takes 0 height.
              ┌──────────────────────────┐
              │ Heading                  │
              │ Paragraph you're reading │  ← you start reading here
              └──────────────────────────┘

Time 800 ms   Image arrives (500px tall). Everything below jumps down.
              ┌──────────────────────────┐
              │ Heading                  │
              │ ███████ image ████████   │
              │ ███████████████████████  │
              │ Paragraph you're reading │  ← pushed down; you lose your place
              └──────────────────────────┘

This jump is called layout shift. Google measures it as Cumulative Layout Shift (CLS), one of the Core Web Vitals. When width and height are present, the browser knows the image's aspect ratio before downloading it and reserves exactly the right space.

Resizing Images with CSS

Should the attributes match the displayed size? Not necessarily. A very common pattern is to give the real dimensions in HTML and let CSS make the image fit its container:

img {
  max-width: 100%;  /* never wider than its container */
  height: auto;     /* keep the aspect ratio */
}

With this CSS, an 800 × 500 image in a 400px-wide column displays at 400 × 250, and the browser still reserves the right space because it knows the ratio 800 : 500 from the attributes. If you set only one of width/height in HTML, or set different values from the real ratio without height: auto, the image may look stretched or squashed.

Displaying a 4000px photo at 400px still downloads the full 4000px file. For really efficient sizing you should serve smaller files to smaller screens — that's covered in Responsive Images: srcset & picture.


Choosing an Image Format

FormatBest forTransparencyAnimationNotes
JPEG (.jpg)PhotographsNoNoLossy; universal support
PNG (.png)Screenshots, diagrams, sharp edgesYesAPNG onlyLossless; large for photos
GIF (.gif)Simple animationsYes (on/off only)YesOnly 256 colours; mostly outdated
WebP (.webp)Photos and graphicsYesYesUsually smaller than JPEG/PNG; all modern browsers
AVIF (.avif)Photos and graphicsYesYesOften smallest; all current major browsers
SVG (.svg)Logos, icons, chartsYesYesVector — sharp at any size; it's XML text

A quick decision guide:

  • Logo or icon? → SVG.
  • Photo? → AVIF or WebP (with a JPEG fallback if you must support very old browsers — see the <picture> element in Responsive Images: srcset & picture).
  • Screenshot or diagram with text? → PNG or lossless WebP.

Lossy compression throws away detail the eye barely notices to make the file smaller; lossless keeps every pixel exactly. That's why JPEG is great for photos but makes text in screenshots look blurry around the edges.


Captions: <figure> and <figcaption>

When an image needs a visible caption — like “Figure 3.2” in a textbook — wrap it in <figure> and add a <figcaption>.

<figure>
  <img src="images/campus.jpg" alt="Four-storey red-brick building with a clock tower" width="400" height="250">
  <figcaption>Fig. 1: The main building of our college.</figcaption>
</figure>

<figcaption> must be the first or last child of <figure>. The caption and the alt do different jobs: the alt describes the image for people who can't see it, while the caption adds context for everyone. Don't just copy one into the other.

A <figure> isn't only for images — it can hold a code listing, a diagram or a table that is referred to from the main text. Browsers indent it with a margin by default.


Lazy Loading

By default, the browser downloads every image on the page as soon as possible, even those far down the page that the user may never scroll to. The loading attribute changes this:

<img src="images/campus.jpg" alt="College main building" width="800" height="500" loading="lazy">
ValueBehaviour
eager (default)Load immediately
lazyWait until the image is close to the visible area

Lazy loading saves data and speeds up the first load. Two rules:

  1. Don't lazy-load images visible on first load (like a hero banner). Delaying them makes the page feel slower and hurts the Largest Contentful Paint metric.
  2. Always set width and height on lazy images, otherwise they cause layout shift when they finally load.

Two related attributes you may meet: fetchpriority="high" hints that an important image (like the hero) should be downloaded before others, and decoding="async" lets the browser decode the image without holding up other content. Both are optional hints.


What Happens When an Image Fails?

<img src="images/does-not-exist.png" alt="Diagram of the TCP three-way handshake" width="300" height="80">

The file doesn't exist, so there is nothing to draw. In Chrome you see a small broken-image icon followed by the alt text, “Diagram of the TCP three-way handshake”, flowing inline like ordinary text. The reader still learns what was supposed to be there — this is why alt text matters even for sighted users. With a meaningless alt like “img1”, the reader would learn nothing.

The exact appearance of a broken image varies between browsers (some show an empty box of the given size, some show only the text), so never design a page that depends on it.

Other common causes of broken images:

  • Wrong path or wrong folder (check ../).
  • Wrong case: Logo.PNG vs logo.png — works on Windows, fails on most Linux web servers.
  • Using a local Windows path like C:\Users\me\photo.jpg, which only exists on your computer.

Worked Example: A Profile Card

Create this structure and put any two images in the images folder with these names:

profile/
├── index.html
└── images/
    ├── campus.jpg     (800 × 500 photo)
    └── logo.png
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Campus Tour</title>
  <style>
    img { max-width: 100%; height: auto; }
  </style>
</head>
<body>
  <a href="index.html"><img src="images/logo.png" alt="Campus Tour home" width="64" height="64"></a>
  <h1>Campus Tour</h1>
  <figure>
    <img src="images/campus.jpg" alt="Red-brick main building with a clock tower and a lawn in front" width="800" height="500">
    <figcaption>Fig. 1: The main building, built in 1965.</figcaption>
  </figure>
  <p>The computer lab is on the second floor.</p>
  <img src="images/lab.jpg" alt="Rows of desktop computers in the lab" width="800" height="500" loading="lazy">
</body>
</html>

What you'll see in the browser:

  • A small 64 × 64 logo at the top-left, which is a link back to the home page.
  • The main heading, then the campus photo — which shrinks to fit if its column is narrower than 800px, thanks to max-width: 100% — indented by the default <figure> margin, with the caption directly below it.
  • The paragraph, and finally the lab image. We didn't create lab.jpg, so you'll see a broken-image icon with the alt text — a deliberate reminder of why alt matters.

Notice the logo has an alt that describes its function (“home”), the campus photo has a descriptive alt and a separate caption, and only the image far down the page is lazy-loaded.


Obsolete Image Attributes

Old code often uses these on <img>. They are deprecated or obsolete; use CSS instead.

Old attributeModern replacement
align="left"CSS float or flexbox
border="0"CSS border
hspace, vspaceCSS margin
nameid
longdescA link to a description, or aria-describedby

Common Mistakes

  • Missing alt, or alt like “image”, “photo”, “pic1”.
  • Units in width/height: width="300px" is invalid — write width="300".
  • Stretching by setting both dimensions to values that don't match the real aspect ratio.
  • Uploading huge photos (5 MB phone pictures) and shrinking them with CSS — the user still downloads 5 MB.
  • Lazy-loading the first visible image.
  • Using title instead of alt. title is just a hover tooltip; it is not a text alternative.
  • Using <img> for pure decoration that belongs in CSS (background-image). Content images go in HTML; decorative backgrounds usually go in CSS.

Interview and Exam Questions

1. Why is the alt attribute important? Give two situations where it is used.

It provides a text alternative to the image. It is read by screen readers for visually impaired users, shown when the image fails to load, and used by search engines to understand the image.

2. What is the difference between alt="" and no alt at all?

alt="" marks the image as decorative, so assistive technology ignores it. A missing alt is an error; screen readers may announce the file name, which is noise for the user.

3. Why should you specify width and height on images?

So the browser can compute the aspect ratio and reserve space before the image downloads, preventing layout shift (a better CLS score). The values are integers in CSS pixels, without units.

4. Which format would you choose for a company logo, a holiday photo and an animated loader?

Logo → SVG (vector, sharp at any size). Photo → AVIF or WebP (or JPEG for maximum compatibility). Animated loader → an animated SVG or CSS animation, or animated WebP; GIF works but is larger and limited to 256 colours.

5. What does loading="lazy" do? When should you avoid it?

It defers loading the image until it is near the viewport. Avoid it for images visible on initial load (e.g. a hero image), because it delays them and hurts Largest Contentful Paint.

6. What is the difference between alt and <figcaption>?

alt replaces the image for people who can't see it; it isn't shown normally. <figcaption> is a visible caption for all users that adds context. They should complement each other, not repeat each other.

7. Is <img> a void element? What does that mean?

Yes. A void element cannot have content and has no end tag. <img>, <br>, <hr>, <input> and <meta> are examples.


Summary

  • <img src="..." alt="..."> embeds an image; it is a void element.
  • Alt text: describe informative images, use alt="" for decorative ones, describe the action for linked images.
  • Always set width and height (integers, no units) to prevent layout shift; resize with CSS max-width: 100%; height: auto.
  • SVG for logos/icons, AVIF/WebP/JPEG for photos, PNG for screenshots.
  • Use <figure> and <figcaption> for captioned images.
  • loading="lazy" for images below the fold, never for the first visible image.
  • Use CSS instead of old attributes like align, border, hspace and vspace.

Next, in Lists, we'll organise content into bulleted, numbered and description lists.