Images & Media
img, picture, srcset, alt text
Skills taught: html.images, html.alt-text, html.responsive-images, html.figure
The **img** element embeds an image. It is a **void element** — it has no closing tag.
<img src="/images/hero.jpg" alt="A developer typing code on a laptop" width="800" height="450">
Warning:
- **src** — path to the image file
- **alt** — text description (required for accessibility)
- **width / height** — explicit dimensions to prevent layout shift
- **loading="lazy"** — defer loading until the image nears the viewport
- **decoding="async"** — decode image off the main thread
<img
src="/images/hero.jpg"
alt="A developer typing code on a laptop"
width="800"
height="450"
loading="lazy"
decoding="async"
>
Use **figure** and **figcaption** to associate a caption with an image:
<figure>
<img src="/images/html-structure.png"
alt="Diagram showing the HTML document tree"
width="600" height="400">
<figcaption>Fig 1. The HTML document tree — html contains head and body.</figcaption>
</figure>
The **picture** element serves different images for different screen sizes or formats:
<picture>
<!-- Serve AVIF to browsers that support it -->
<source srcset="/images/hero.avif" type="image/avif">
<!-- Fall back to WebP -->
<source srcset="/images/hero.webp" type="image/webp">
<!-- Final fallback: plain JPEG -->
<img src="/images/hero.jpg" alt="Hero image" width="800" height="450">
</picture>
Tip:
Frequently Asked Questions
What image format should I use?
Use AVIF first (best compression), WebP as fallback, then JPEG for photos or PNG for transparency. Use the picture element to serve AVIF/WebP with a JPEG/PNG fallback.
What's the difference between loading=lazy and loading=eager?
lazy defers the image request until the user scrolls near it — great for images below the fold. eager (the default) loads the image immediately. Never lazy-load the largest above-the-fold image (your LCP image).
Can I use SVG as an img source?
Yes. <img src="logo.svg"> works in all modern browsers. SVG is ideal for logos and icons as it scales without quality loss.