`<img>` With `alt`, `width`/`height`, `loading="lazy"`
Images
An `<img>` needs an `src` and an `alt`. Setting dimensions prevents layout shift; `loading="lazy"` helps performance.
What you'll learn
- Use `<img>` correctly
- Write good `alt` text
- Pick `<picture>` for art-directed images
<img> is a void element — no closing tag. The two required-ish
attributes are src (the file) and alt (the text alternative).
The Basics
<img src="/cats/whiskers.jpg" alt="A grey cat napping in a sunbeam" /> Alt Text — Required Always
alt is the text shown when the image can’t load and the text
read aloud by screen readers. Every meaningful <img> needs it.
| Image kind | alt value |
|---|---|
| Conveys information (a chart, a portrait) | A short description of what it shows |
| Decorative (a divider, a background-only image) | Empty: alt="" |
| Image is inside a link with no other text | Describe where the link goes |
| Already labeled by surrounding text | Empty: alt="" |
Empty alt is not “missing alt” — it explicitly tells screen readers to ignore the image. Use it for decorative-only images.
Width and Height — Prevent Layout Shift
Set width and height to the image’s intrinsic dimensions:
<img src="/hero.jpg" alt="" width="1600" height="900" /> The browser reserves space at the right aspect ratio before the image loads. Without these, content below jumps around as images load — bad UX and bad Core Web Vitals.
Lazy Loading
<img src="/big-photo.jpg" alt="..." width="800" height="600" loading="lazy" /> Below-the-fold images load only when scrolled near. Free performance win.
Responsive Images With srcset
For images that should adapt to screen size:
<img
src="/hero-1600.jpg"
srcset="
/hero-800.jpg 800w,
/hero-1200.jpg 1200w,
/hero-1600.jpg 1600w
"
sizes="(max-width: 600px) 100vw, 60vw"
alt=""
width="1600"
height="900"
/> The browser picks the right source based on screen width and pixel density.
<picture> For Art Direction
When you need a different crop or completely different image at different breakpoints:
<picture>
<source media="(max-width: 600px)" srcset="/hero-portrait.jpg" />
<source media="(min-width: 601px)" srcset="/hero-wide.jpg" />
<img src="/hero-wide.jpg" alt="" width="1600" height="900" />
</picture> The browser picks the first matching <source>. The <img> inside
is the fallback.
Format Negotiation
<picture> also handles WebP/AVIF:
<picture>
<source type="image/avif" srcset="/hero.avif" />
<source type="image/webp" srcset="/hero.webp" />
<img src="/hero.jpg" alt="" />
</picture> End of Chapter
That wraps HTML foundations. Next chapter: tables, forms, media, and the semantic structural elements.
Tables →