09
HTML – Images
Chapter 9 • Beginner
20 min
Images make web pages more attractive, informative, and engaging. In HTML, images are added using the <img> tag.
The <img> tag
The <img> tag is an empty (void) element. It does not have a closing tag.
Basic example:
- <img src="photo.jpg" alt="My photo">
Important attributes:
- src (source)
- URL/path of the image file.
- Can be a local file path (relative) or an external URL.
- alt (alternative text)
- Text shown if the image can’t load.
- Read aloud by screen readers for visually impaired users.
- Very important for accessibility and SEO.
- width and height
- Set the size of the image.
- Values are usually in pixels.
- Example: width="300" height="200"
- title (optional)
- Shows a tooltip when you hover over the image.
Image formats
Common image file types:
- .jpg or .jpeg – good for photos
- .png – supports transparency, good for icons/logos
- .gif – simple animations
- .svg – scalable vector graphics (great for logos, icons, and diagrams)
Good practices
- Always provide a meaningful alt text (describe the image).
- Use appropriate sizes to avoid huge image files that slow down the page.
- Use CSS for advanced styling (borders, shadows, alignment) instead of old attributes like border and align.
Example of bad vs better alt:
- Bad: alt="image1"
- Better: alt="Student writing code on a laptop"
Suggested image prompt
"Simple web page screenshot showing a header and an image of a laptop with alt text, plus a diagram labeling src, alt, width, and height attributes on the <img> tag."
Interview-style questions from this topic
- Which tag is used to display images in HTML?
- What is the purpose of the alt attribute on images?
- What happens if the image file in src is missing?
- When would you use PNG instead of JPG?
- Why is alt text important for accessibility and SEO?
Hands-on Examples
Basic Image Example
<!DOCTYPE html>
<html>
<head>
<title>Image Example</title>
</head>
<body>
<h1>Image Example</h1>
<img src="https://via.placeholder.com/300x200" alt="Sample placeholder image">
</body>
</html>This example adds an image using the <img> tag. The src attribute points to an online placeholder image, and the alt attribute describes the image. If the image fails to load, the alt text will be shown instead.