HTML Images
The image tag, written as img, puts a picture on your page. It is a void element, which means it has no content and no closing tag. Everything about the image lives in attributes: src holds the file location, and alt holds a text description. That makes img the most attribute-driven tag you will meet.
The src attribute is the whole show. Point it at a file on your own server, like images/logo.png, or at a full web address for an image hosted elsewhere. Get the path wrong and the browser shows a broken image icon. Relative paths are the safer habit for images that belong to your own site.
The alt attribute matters almost as much as src. It shows in place of the image when the file fails to load, and screen readers speak it aloud for people who cannot see the picture. Search engines read alt text to understand the image too. Write a short, honest description of what the photo shows, and use an empty alt for decorative images.
Sizing images
Images load at their natural size, which is often far too large for the page. The width and height attributes set exact dimensions, and a CSS width like 100% makes the image shrink to fit any screen. Setting the dimensions ahead of time also stops the layout from jumping while the image loads.
<img src="photo.jpg" alt="Mountain lake at sunset" width="400">
Writing good alt text
Good alt text is short and specific. Say what the image shows, not what kind of image it is. A photo of a team meeting gets alt text about the meeting, not the word photo. A decorative image that adds no information can use an empty alt with two quotes, which tells screen readers to skip it.
<img src="decorative-line.png" alt="">
Syntax
<img src="photo.jpg" alt="A description of the photo">
Missing width/height Causes Layout Shift (CLS) Even With CSS
Omitting width and height on <img> forces the browser to reflow text after the image loads, spiking Core Web Vitals CLS and hurting SEO. New advice since 2020: always add width/height attributes and control size with CSS (height:auto). Also, alt="" for decorative images prevents screen readers gabbling 'image' endlessly.
<img src="cat.jpg" width="600" height="400" alt="cat" style="width:100%;height:auto">
Good to know
- img is a void tag with no closing tag.
- src points to the image file, alt describes it.
- Set dimensions so the layout does not jump while loading.
- Use empty alt text for purely decorative images.