Images in HTML
Embed images correctly, write meaningful alt text, and let responsive images pick the right file for the screen.
អាន 2 នាទី
The <img> tag
<img src="cat.jpg" alt="A orange tabby cat sleeping on a windowsill" /><img> is self-closing — it has no content or closing tag, only attributes.
src— the path to the image file (relative or absolute, same rules as links).alt— a text description of the image, shown if the image fails to load and read aloud by screen readers.
Alt text is not optional
Every meaningful <img> needs an alt attribute. Skipping it, or filling it with something useless like alt="image", leaves screen reader users with no idea what's on the page — and search engines can't index the image either.
Write alt text that describes the image's purpose in context, not just its literal contents:
<!-- A logo linking to the homepage -->
<img src="logo.png" alt="Acme Inc. home" />
<!-- A purely decorative image with no informational value -->
<img src="divider-swirl.png" alt="" />An empty alt="" is the correct choice for purely decorative images — it tells screen readers to skip the image entirely, rather than reading out a meaningless filename.
Sizing images
<img src="banner.jpg" alt="Summer sale banner" width="800" height="400" />Setting width and height doesn't force the image to that size in modern responsive layouts (CSS usually handles the actual display size) — but it does tell the browser the image's aspect ratio before it downloads, so the page can reserve the right amount of space and avoid content jumping around as images load in.
Responsive images with srcset
A single image file is often wasteful — a phone doesn't need the same resolution as a 4K monitor. srcset lets the browser choose:
<img
src="photo-800w.jpg"
srcset="photo-400w.jpg 400w, photo-800w.jpg 800w, photo-1200w.jpg 1200w"
sizes="(max-width: 600px) 100vw, 50vw"
alt="Mountain landscape at sunset"
/>The browser picks whichever file best matches the device's screen size and pixel density, saving bandwidth on smaller screens without any JavaScript involved.
Figures and captions
When an image needs a caption, wrap both in <figure>:
<figure>
<img src="chart.png" alt="Bar chart of quarterly revenue" />
<figcaption>Revenue grew 18% quarter-over-quarter.</figcaption>
</figure><figcaption> is explicitly linked to its <figure>, which is more meaningful than a plain <p> sitting next to an image.