HTML Images: img, alt Text, Sizes and figure
The <img> element embeds a picture. It is a void element, so it has no closing tag; everything it needs is in its attributes.
The essential attributes
srcis the image's URL. The example usesdata:URLs that contain small SVG drawings inline, so it works without any files.altis the text alternative. Screen readers read it aloud, and browsers show it if the image fails to load.widthandheightgive the image's dimensions in pixels. Browsers use them to reserve space before the image downloads, so the text below does not jump when it arrives. That jump is called layout shift, and Google's Core Web Vitals measure it.
Writing alt text
Describe what the image communicates in context, not just what it shows. For a chart, the useful alt text is the data: "Bar chart: Python 22 chapters, JavaScript 19, SQL 14", not "chart". For a purely decorative image that adds no information, use an empty alt="", which tells screen readers to skip it. Never leave alt out altogether; some screen readers then read the file name.
Expected page text
Chapters per track Images are inline elements, so text can flow next to them.
The page text in the expected output contains only the caption and the paragraph. Alt text is not part of the page's visible text, which is exactly why it must stand on its own for people who cannot see the image.
figure and figcaption
<figure> groups self-contained content, such as an image, chart or code sample, with an optional <figcaption> that describes it. The caption is visible to everyone, while alt replaces the image for those who cannot see it. They often say different things.
Performance
loading="lazy"delays offscreen images until the user scrolls near them. Do not lazy-load the main image at the top of the page.srcsetandsizesoffer several widths of the same image so phones download smaller files. The<picture>element adds modern formats like AVIF and WebP with a fallback.- Use SVG for logos and icons; it stays sharp at any size.
Common mistakes
- Missing
alt, or alt text such as "image" or "photo". - Leaving out
widthandheight, causing layout shift. - Uploading a 4000-pixel photo to display at 400 pixels wide.
Summary
<img src alt width height>is the minimum for every image.- Alt text conveys the image's purpose; decorative images use
alt="". figure+figcaptionadd a visible caption.- Lazy-load offscreen images and serve sizes that match the layout.
Quiz: Images