HTML Tutorial · HTML Basics · Lesson 7 of 34
HTML Images
Add images with alt text, sizes, lazy loading and responsive sources.
The img element
<img> is a void element with two essential attributes:
src— the image URL.alt— a text alternative, read by screen readers and shown if the image fails. Describe the image's purpose; usealt=""for purely decorative images.
<img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='240' height='120'%3E%3Crect width='240' height='120' rx='12' fill='%232563eb'/%3E%3Ctext x='120' y='70' font-size='28' text-anchor='middle' fill='white' font-family='sans-serif'%3EReadyCamel%3C/text%3E%3C/svg%3E"
alt="ReadyCamel logo: white text on a blue rounded rectangle" width="240" height="120">
<p>
<img src="missing.png" alt="This alt text appears because the image is missing" width="200" height="60">
</p>
Performance
- Set
widthandheightso the browser reserves space and the page doesn't jump while loading. loading="lazy"delays off-screen images.- Use modern formats (WebP, AVIF) and appropriately sized files.
Responsive images and figures
srcset and sizes let the browser pick the best file for the screen. <figure> with <figcaption> groups an image with its caption:
<figure>
<img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='300' height='150'%3E%3Crect width='300' height='150' fill='%2310b981'/%3E%3Ccircle cx='150' cy='75' r='45' fill='white'/%3E%3C/svg%3E"
srcset="photo-600.webp 600w, photo-1200.webp 1200w"
sizes="(max-width: 600px) 100vw, 600px"
alt="A white circle on a green background" width="300" height="150" loading="lazy">
<figcaption>Figure 1: An image with a caption.</figcaption>
</figure>
Test yourself
Which attribute provides a text alternative for an image?
titlealtcaptiondescription
Show answer
Answer: alt