Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Images

Images make a page clearer: product photos, diagrams, logos. The image itself is a separate file, and HTML only tells the browser where to get it and how to describe it in words.

The img tag

The <img> tag (from image) is void. The src attribute (source) holds the file address, and alt holds a text description:

<img src="/icons/languages/html-css.png" alt="The HTML and CSS logo">

The address in src works the same way as in links: it can be absolute or relative.

The alt text

The text in alt is shown to the user if the image fails to load, and read aloud to someone using a screen reader. Here the file does not exist — and the browser shows the description:

<img src="/no-such-file.png" alt="A cup of cappuccino with a heart drawn in the foam">

Describe what is shown and why the image is on the page. For purely decorative images write an empty alt="" — a screen reader will then skip it.

Sizes

The width and height attributes set the width and height in pixels:

<img src="/icons/languages/python.png" alt="Python" width="48" height="48">
<img src="/icons/languages/python.png" alt="Python" width="96" height="96">

Even if you change the size in CSS, it is worth setting these attributes: the browser reserves space for the image in advance, and the text does not "jump" while it loads.

An image with a caption

<figure> groups an image with its caption, and <figcaption> is the caption itself:

<figure>
  <img src="/icons/languages/javascript.png" alt="The JavaScript logo" width="80" height="80">
  <figcaption>Fig. 1. The JavaScript language logo</figcaption>
</figure>

Everyone sees the caption, while alt appears only when the image is missing. So the two should not repeat each other.

Formats and loading

FormatWhat for
JPEG (.jpg)Photos
PNG (.png)Screenshots, images with transparency
WebP, AVIFA modern replacement for both: smaller files at the same quality
SVG (.svg)Icons and logos — sharp at any size

The loading="lazy" attribute delays loading the image until the user scrolls near it:

<p style="height: 200px;">Scroll down...</p>
<img src="/icons/languages/go.png" alt="The Go logo" width="64" height="64" loading="lazy">

Do not set it on images at the top of the page — they are needed right away.

You can put an image inside <a> — then it becomes clickable:

<a href="https://go.dev">
  <img src="/icons/languages/go.png" alt="The Go language website" width="48" height="48">
</a>

For such an image alt describes where the link leads, not what is drawn.

Common mistake

Without alt a screen reader reads out the file name — something like "IMG 2041 dot jpg". Do not write the words "image" or "photo" in alt either: that is already obvious. Bad — alt="photo", good — alt="Anna behind the coffee shop counter".

Thanks for reading!

Donate to the site — we work hard for you.