The img Tag
Learn how to add images to your web pages using the HTML img tag with proper attributes.
The img Tag
Images make web pages visually appealing. The <img> tag is how you embed images in HTML.
Basic Syntax
<img src="photo.jpg" alt="A beautiful sunset">
The <img> tag is a self-closing element — it has no closing tag.
Required Attributes
| Attribute | Purpose | Required? |
|---|---|---|
src | Path or URL to the image file | ✅ Yes |
alt | Alternative text describing the image | ✅ Yes (for accessibility) |
Optional Attributes
| Attribute | Purpose |
|---|---|
width | Sets the image width (in pixels) |
height | Sets the image height (in pixels) |
title | Tooltip text shown on hover |
loading | Set to "lazy" for lazy loading |
Types of Image Paths
<!-- Same folder -->
<img src="photo.jpg" alt="Photo">
<!-- Subfolder -->
<img src="images/photo.jpg" alt="Photo">
<!-- Parent folder -->
<img src="../photo.jpg" alt="Photo">
<!-- External URL -->
<img src="https://example.com/photo.jpg" alt="Photo">
Why the alt Attribute Matters
- Accessibility — screen readers read the alt text to visually impaired users
- Broken images — alt text is shown if the image fails to load
- SEO — search engines use alt text to understand what the image shows
Writing Good alt Text
| ✅ Good | ❌ Bad |
|---|---|
alt="Golden retriever playing in a park" | alt="dog" |
alt="HTML code example in VS Code" | alt="image1" |
alt="" (for decorative images) | alt="photo.jpg" |
Supported Image Formats
- JPEG (.jpg) — best for photographs
- PNG (.png) — best for graphics with transparency
- GIF (.gif) — for simple animations
- SVG (.svg) — for scalable vector graphics (icons, logos)
- WebP (.webp) — modern format with better compression
Key Takeaways
- Use
<img src="..." alt="...">to add images - Always include an
altattribute for accessibility srccan be a relative path or an absolute URL- Use
widthandheightto control image size - Choose the right image format for your use case