HTML Images
Images are one of the most common ways to make a web page visual and engaging, and in HTML they are added with a single, self-contained element: <img>. Unlike most HTML elements, <img> doesn’t wrap around content — it points to an external image file and tells the browser to fetch and display it inline with the surrounding text. Understanding exactly how this element works, and how to describe images properly for accessibility and performance, is essential for building real web pages.
Overview: How Images Work in HTML
The <img> element is a replaced element and a void element. “Replaced” means the browser doesn’t render the element’s own markup directly — instead, it fetches an external resource (the image file) and substitutes it into the layout in place of the tag. “Void” means the tag never has a closing tag or children; it is self-contained, written as <img src="..." alt="..."> with no </img>.
When the HTML parser encounters an <img> tag, it creates a corresponding node in the DOM tree immediately, but the actual image bytes are requested separately over the network (or from the browser cache) as soon as the parser sees the src attribute. This means image loading is asynchronous relative to HTML parsing: the rest of the page continues to be parsed and rendered while the image downloads in the background. Once the image data arrives and is decoded, the browser reflows the layout (if the image’s dimensions weren’t already reserved via width/height) and paints the picture into the page.
By default, <img> is an inline-level replaced element. That means it behaves somewhat like a piece of text — it can sit in the middle of a paragraph, next to other inline content — but because it is replaced, it has an intrinsic width and height from the image file itself, unlike normal text. If you want an image to behave like a full block (its own line, full control over margins), that’s a job for CSS (e.g. display: block), not HTML — this course covers structure and semantics; visual styling belongs to CSS.
Syntax
The basic form of an image element looks like this:
<img src="path/to/image.jpg" alt="Description of the image" width="400" height="300">
Key attributes:
| Attribute | Purpose |
|---|---|
src |
Required. The path or URL to the image file (relative or absolute). |
alt |
Required for accessibility. Text describing the image, read by screen readers and shown if the image fails to load. |
width |
The rendered width in pixels. Helps the browser reserve space before the image loads. |
height |
The rendered height in pixels. Used together with width to preserve the image’s aspect ratio. |
title |
Optional tooltip text shown on mouse hover. |
loading |
Controls when the browser fetches the image: eager (default, load immediately) or lazy (defer loading until near the viewport). |
srcset |
A list of image candidates at different resolutions/widths, letting the browser pick the best one for the current screen. |
sizes |
Describes how wide the image will be displayed at different viewport widths, used alongside srcset. |
Examples
Example 1: A Basic Image
<p>Here is a photo from our trip:</p>
<img src="mountain.jpg" alt="Snow-capped mountain peak at sunrise" width="500" height="350">
Result: The paragraph text appears, followed on the next line by the mountain photo rendered at 500 by 350 pixels. If the file mountain.jpg cannot be found, the browser instead displays a small broken-image icon along with the alt text “Snow-capped mountain peak at sunrise”.
This is the simplest possible use of <img>: a required src pointing to the file, an alt describing it in words, and explicit dimensions so the browser can reserve the right amount of space in the layout before the file finishes downloading.
Example 2: Image Inside a Figure with a Caption
<figure>
<img src="chart-sales.png" alt="Bar chart showing quarterly sales rising from Q1 to Q4" width="600" height="400">
<figcaption>Figure 1: Quarterly sales growth, 2025</figcaption>
</figure>
Result: The chart image is displayed at 600 by 400 pixels, with a smaller line of caption text, “Figure 1: Quarterly sales growth, 2025”, shown directly beneath it. Browsers group the image and caption together as one semantic unit.
The <figure> element is the semantically correct wrapper whenever an image needs a caption. It tells both the browser’s accessibility tree and any reader that the <figcaption> text is describing the media next to it, rather than being an unrelated paragraph.
Example 3: A Responsive Image with srcset
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
sizes="(max-width: 600px) 100vw, 800px"
alt="Portrait of a golden retriever sitting in a park"
width="800"
height="600"
loading="lazy">
Result: On a narrow phone screen, the browser downloads and displays photo-400.jpg; on a wide desktop screen it downloads photo-1600.jpg instead — visually it is the same dog photo, just served at a resolution matched to the screen, and it only begins loading once it scrolls near the visible viewport.
The srcset attribute lists multiple versions of the same image along with their real pixel widths (400w, 800w, 1600w). The sizes attribute tells the browser how large the image will actually be displayed at different viewport widths, so it can calculate which candidate in srcset best matches the screen’s pixel density without downloading more data than necessary. The plain src attribute remains as a fallback for browsers that don’t support srcset.
How It Works Step by Step
- The HTML parser reaches the
<img>tag and immediately inserts an image node into the DOM tree, even before any bytes of the picture have arrived. - The browser starts a network request for the URL in
src(or picks a candidate fromsrcset), often in parallel with other resource requests, and continues parsing the rest of the document. - If
widthandheightare present, the browser reserves that exact box in the layout right away, preventing the surrounding content from jumping around later — this is often called avoiding “layout shift.” - Once the image data downloads, the browser decodes it (JPEG, PNG, GIF, SVG, WebP, etc. each have their own decoder) and paints the pixels into the reserved box.
- If the request fails, or if
srcis missing or invalid, the browser renders the fallback broken-image icon and displays thealttext in its place.
Common Mistakes
Mistake 1: Omitting the alt Attribute
<img src="logo.png">
This is technically valid HTML, but it is a serious accessibility failure: screen readers have nothing to announce, and if the image fails to load, sighted users see nothing meaningful either. Always describe the image’s content or purpose:
<img src="logo.png" alt="Programming Line logo">
Mistake 2: Treating img as a Container Element
<img src="banner.jpg" alt="Site banner">
Welcome to our site!
</img>
Because <img> is a void element, it can never wrap other content, and adding a closing </img> tag like this is invalid markup that a browser will simply ignore or mis-parse. Text and images are separate elements placed side by side, not nested:
<img src="banner.jpg" alt="Site banner">
<p>Welcome to our site!</p>
Mistake 3: Forgetting width and height
Leaving out width and height means the browser doesn’t know the image’s dimensions until it finishes downloading, so the page layout can suddenly shift and push content around as each image finishes loading — a jarring experience for readers. Always include the image’s real pixel dimensions (or its correct aspect ratio) so space is reserved from the start.
Best Practices
- Always include a meaningful
altattribute; usealt=""(empty, but present) only for purely decorative images that carry no information. - Specify
widthandheightto prevent layout shift while images load. - Use
<figure>and<figcaption>whenever an image needs a caption, so the relationship is explicit in the markup. - Use
srcset/sizesfor responsive images that need to look sharp across phone, tablet, and desktop screens without over-downloading data. - Add
loading="lazy"on images that appear below the initial viewport to speed up the page’s initial load. - Choose the right file format for the content: photographs generally suit JPEG or WebP, graphics with flat colors or transparency suit PNG or SVG.
- Keep image file names and
alttext descriptive — this also helps search engines understand page content.
Practice Exercises
- Add an
<img>element that displays a photo of a bicycle, including a correctsrc, a descriptivealt, and explicitwidth/heightattributes. - Wrap that image in a
<figure>element and add a<figcaption>reading “My commuter bike”. - Write an
<img>with asrcsetoffering three widths (e.g. 300w, 600w, 1200w) of the same photo, plus asizesattribute stating it displays at full viewport width on screens under 500px and at 600px otherwise.
Summary
- The
<img>element is a void, replaced, inline-level element that embeds an external image file into the page. srcandaltare essential on every image;altsupports accessibility and provides a fallback if the image fails to load.widthandheightreserve layout space and prevent content from jumping as images load.<figure>and<figcaption>are the correct semantic wrapper for a captioned image.srcsetandsizeslet the browser choose the best image resolution for the current screen, improving both sharpness and performance.- Visual sizing, borders, and positioning belong to CSS — HTML only describes what the image is and where it sits in the document.
