The img Element
Images are embedded using the <img> element, a void element with no closing tag. The src attribute points to the image file, and alt provides a text alternative.
Basic Image
<img src="photo.jpg" alt="A sunset over the mountains" />Common Attributes
| Attribute | Purpose |
|---|---|
| src | Path to the image file |
| alt | Text alternative for accessibility and when the image fails to load |
| width / height | Sets the display dimensions in pixels |
| loading | "lazy" defers loading offscreen images |
Why alt Text Matters
The alt attribute is read aloud by screen readers, displayed if the image fails to load, and used by search engines to understand image content. Every meaningful image should have descriptive alt text.
Decorative Images
<!-- Purely decorative image: use an empty alt so screen readers skip it -->
<img src="divider.png" alt="" />Setting Dimensions
Specifying width and height helps the browser reserve space for the image before it loads, preventing content from jumping around as the page renders (layout shift).
Width and Height
<img src="logo.png" alt="Company logo" width="200" height="80" />Lazy Loading
The loading="lazy" attribute tells the browser to defer loading images that are outside the initial viewport, improving page load performance.
Lazy Loading Example
<img src="gallery-1.jpg" alt="Gallery photo 1" loading="lazy" />Never Skip alt
Omitting the alt attribute entirely (rather than setting it to an empty string) is a common accessibility mistake — screen readers may read out the full file name instead.
Best Practice
Use descriptive alt text for meaningful images, an empty alt="" for purely decorative ones, and always set width/height to avoid layout shift.