Sub topic 8
Adding images with img
This chapter assumes you can write a basic HTML document (html, head, body), open it in a browser, and read file and folder paths. It also assumes you know what an element and an attribute are.
The img element
The img element embeds an image in a page. It is a void element. It has no content and no closing tag. Everything it needs goes in attributes.
<img src="images/red-fox.jpg" alt="A red fox standing in snow">Two attributes matter most:
srcis the location of the image file. It is required.altis text that stands in for the image. It is required for valid, accessible HTML.
How the browser loads an image
The browser reads your HTML, finds the img element, and sends a separate request for the file named in src. It then draws the image inline, in the flow of the text.
Writing the src value
The src value follows the same URL rules as href on links. You can use any of the three forms.
<img src="images/red-fox.jpg" alt="A red fox standing in snow">
<img src="/images/red-fox.jpg" alt="A red fox standing in snow">
<img src="https://example.com/images/red-fox.jpg" alt="A red fox standing in snow">| Form | Example | Resolved from |
|---|---|---|
| Relative | `images/red-fox.jpg` | The folder of the current page |
| Root-relative | `/images/red-fox.jpg` | The root of the site |
| Absolute | `https://example.com/images/red-fox.jpg` | Its own full address |
Prefer relative or root-relative paths for your own images. Linking to an image on someone else's server ties your page to their uptime and may break when they move the file.
Common errors
- Broken image icon. The path is wrong. Check the folder name, the file name, and the extension. On many servers paths are case-sensitive, so
Fox.JPGandfox.jpgare different files. - Missing
alt. A screen reader may read out the file name instead. Search engines also get less information about the image. - Wrong relative path. A relative path is resolved from the page that contains it, not from the CSS file or the project root. If a page lives in
blog/,images/fox.jpgpoints toblog/images/fox.jpg. - Wrong file format. Use JPEG for photos, PNG for images that need sharp edges or transparency, SVG for logos and icons, and WebP or AVIF for smaller files in modern browsers.
Reserving space
An image has no size until it downloads, so the page can jump when it arrives. Adding width and height lets the browser reserve space first. A later chapter covers this together with lazy loading.
Exercise
A page at /blog/post.html contains <img src="images/cat.jpg" alt="A grey cat">. The file is actually at /images/cat.jpg. Why is the image broken, and what is the fix?
Show answer
The relative path images/cat.jpg is resolved from the page's folder, so the browser looks for /blog/images/cat.jpg. Fix it with a root-relative path (src="/images/cat.jpg") or a relative path that goes up one folder (src="../images/cat.jpg").