How to Add Alt Text in HTML
The code is one attribute on the image tag. Here's a complete image, then the variations you'll meet on a real page.
The basic form
<img src="lighthouse.jpg" alt="A white lighthouse on a cliff.">
MDN says every img element needs at least two attributes, most commonly src and alt. It calls the alt attribute mandatory.1
The HTML standard agrees, with exceptions it sets out separately. Unless one of those applies, the alt attribute must be there and must hold an appropriate replacement for the image.2
The attribute goes inside the tag, after the src. Put the text between double quotes, as in the example.
[fig:add-flow]
Images that need no text
Some images should still carry the attribute, with nothing inside the quotes.
<img src="divider.png" alt="">
Wikipedia notes that the W3C recommends an alt attribute on every image, though it does not need to contain text.3 Which images get the empty version is explained in the guide to empty alt.
A linked image
Wrap the img in an a tag and the alt text becomes the link's label.
<a href="/contact/"><img src="envelope.png" alt="Contact us"></a>
The HTML standard has a rule for links and buttons that hold only images. Between them, the images' alt attributes have to say what the link or button is for.2 MDN says to describe the resource the link points to, as you would with a text link.1 The logos and icons page has more cases.
An image button in a form
WebAIM gives an example of an image button on a site search form.4
<input type="image" src="search.png" alt="Submit Search">
Here the alt describes what the button does.4
An image with a caption
Use a figure element with a figcaption. MDN says that's the way to caption an image.1
<figure>
<img src="shelf.jpg" alt="A wooden shelf of folders.">
<figcaption>Our filing shelf.</figcaption>
</figure>
The img inside still needs its own alt text. WebAIM says so directly.4 Don't copy the caption into the alt attribute, and don't expect one to do the other's job. Writing alt text step by step shows how they differ.
Things that aren't a substitute
The title attribute. MDN says it isn't an acceptable substitute for alt.1
CSS background images. WebAIM says it's not possible to add alternative text directly to a CSS background image.4 If a background image carries content, the content has to be made available in the page itself.4
If you use a website builder
If you edit pages in a website builder instead of raw code, its help pages will show where the alt text goes. The builder may write the HTML for you. The advice on writing the words is the same either way, and the other pages here cover it. Start with what alt text is if you haven't read it.
Reference list
- <img>: The Image Embed element, MDN Web Docs, Mozilla
- HTML Standard, the img element and alternative text, WHATWG
- alt attribute, Wikipedia
- WebAIM: Alternative Text, WebAIM, Utah State University