Adding images
Add images with <img> and the src and alt attributes.
The img element
The <img> element adds an image to the page. Unlike most elements, it has no closing tag: it is a void element. On its own <img> shows nothing; you must give the image address with the src attribute.
The address can be a URL: a web address (for example https://example.com/landscapes/lake.jpg) or a file path inside your own site (for example img/lake.jpg). The browser requests that address and renders the image on the page.
The alt attribute
The alt attribute carries a text description of the image. If the image cannot load (wrong address, slow connection, blocked images) this text is shown instead. Screen-reader users also recognise the image from this text.
The content should be meaningful: alt="Sunset by the lake" is good; alt="image" is weak. If the image is purely decorative, use alt="" to tell the screen reader to skip it.
Exercise Add an image
Add an <img> element to body. Write a realistic image address in src and a short description in alt.
Show example solution
<body>
<img src="https://example.com/landscapes/lake.jpg" alt="Sunset by the lake">
</body>
Test yourself
-
Which attribute gives the file address of an image?
- title
- src
- alt
- href
Show answer
src — Correct. The src attribute carries the image address; the browser loads it from there.
-
Write the src attribute in the img tag
<img ____="https://example.com/city/square.jpg" alt="City square">Show answer
<img src="https://example.com/city/square.jpg" alt="City square"> -
Match each attribute to its role
- src
- Image address
- alt
- Image text description
- href
- Link address (a element)
- title
- Tooltip on hover