HTML Images

What Is the <img> Tag?

The <img> tag embeds images in web pages. It is a self-closing (void) element and must include at least a source and alternate text.

Basic Syntax

<img src="cat.jpg" alt="A cat sitting on a windowsill">

The src points to the image file, while alt provides a textual description if the image fails to load or for screen readers.

Required Attributes

  • src – Path or URL to the image
  • alt – Descriptive alternative text (crucial for accessibility and SEO)

Optional Attributes

  • width and height – Control display size (e.g., pixels or %)
  • title – Tooltip text shown on hover
  • loading="lazy" – Defers loading for performance (especially for images off-screen)
<img src="photo.jpg" alt="Sample" width="200" height="150" loading="lazy">

Relative vs Absolute Paths

Images can be loaded using:

  • Relative path: src="images/logo.png" (within your project)
  • Absolute URL: src="https://example.com/logo.png" (external file)

Best Practices

  • ✅ Always include descriptive alt text
  • 🚀 Compress images for faster loading
  • 📱 Use responsive techniques or media queries
  • 🖼️ Consider using modern formats (e.g., WebP) for better performance

Practice Prompt

Embed an image using the following criteria:

  • Use an external image URL
  • Set width to 300 and height to 200
  • Use meaningful alt text
  • Add CSS to make it responsive
<img src="https://example.com/dog.jpg" 
     alt="Golden retriever running through a field" 
     width="300" height="200">

<style>
  img {
    max-width: 100%;
    height: auto;
  }
</style>

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic