Sub topic 11
Turning an image into a link
This chapter assumes you can write an a element with an href, and that you know how img and its alt attribute work. Here you combine the two.
Wrapping an image in an anchor
An a element can contain more than text. If you place an img inside it, the whole image becomes clickable.
<a href="/">
<img src="images/logo.svg" alt="Example Co. home" width="120" height="40">
</a>The href works exactly as it does for a text link. The relative path in src is resolved the same way as any other URL, so the rules from the URL chapter still apply.
Alt text becomes the link text
A screen reader announces a link by its accessible name. When the image is the only content of the link, the alt text is that name. So the alt should describe where the link goes, not what the picture looks like.
| Alt text | What a screen reader announces | Verdict |
|---|---|---|
| `alt="Blue logo with a white star"` | "link, Blue logo with a white star" | Describes the picture, not the destination |
| `alt=""` | "link" followed by the file name or the URL | No usable name |
| `alt="Example Co. home"` | "link, Example Co. home" | Describes the destination |
An empty alt is correct for a decorative image. Inside a link that has no other content, it leaves the link without a name.
Combining an image with text
Often a link holds both an image and text, such as a card with a thumbnail and a headline. Put both in one a element. Then give the image an empty alt, because the text already names the link. Otherwise the screen reader reads the same words twice.
<a href="articles/red-foxes.html">
<img src="images/red-fox-thumb.jpg" alt="" width="160" height="107">
<span>How red foxes survive the winter</span>
</a>Do not use two separate links, one around the image and one around the text, that point to the same page. Keyboard users have to tab through both, and screen reader users hear the same destination twice.
Common errors
- Writing
alt="logo". The link is announced as "logo", which says nothing about its destination. - Putting the
ainside theimg. Theimgelement is void and cannot contain anything, so the anchor must wrap the image. - Leaving out
widthandheight. A linked image that loads late shifts the page, and users may click the wrong target. - Making the clickable area unclear. Keep the focus outline that browsers draw around a focused link. Keyboard users rely on it to see which image is active.
Exercise
A product card contains a photo of a lamp and the text "Oak desk lamp", both inside one a element that points to /products/oak-lamp.html. What should the alt value of the photo be, and why?
Show answer
Use an empty alt (alt=""). The visible text "Oak desk lamp" already gives the link its accessible name. A non-empty alt would make a screen reader announce the same information twice.