Tag img

The img tag is used to embed images into an HTML document. It is a self-closing tag, which means it doesn’t need a closing </img>.


🔧 Syntax:

<img src="path_to_image" alt="alternative text">

🧩 Key Attributes:

AttributeDescription
srcRequired. Specifies the path to the image (can be relative or absolute).
altRequired for accessibility. Describes the image content; displayed if the image fails to load.
widthOptional. Sets the image width (in pixels or percentage).
heightOptional. Sets the image height.
titleOptional. Tooltip text that appears when you hover over the image.
loadingOptional. Controls image loading behavior (lazy or eager).

✅ Example:

<img src="https://example.com/dog.jpg" alt="A dog on the lawn" width="400" height="300">

📱 Responsive Images:

To make images responsive, use CSS:

<img src="cat.jpg" alt="A cat" style="max-width: 100%; height: auto;">

Or use the <picture> element for different screen sizes:

<picture>
<source srcset="image-large.jpg" media="(min-width: 800px)">
<source srcset="image-small.jpg" media="(max-width: 799px)">
<img src="image-fallback.jpg" alt="Image description">
</picture>

🛡️ Importance of alt:

  • Enhances accessibility for screen readers.
  • Improves SEO since search engines read the alt attribute.
  • Provides context if the image fails to load.

🧠 Best Practices:

  • Use optimized image formats like WebP or AVIF for faster loading.
  • Always include meaningful alt text.
  • Use loading="lazy" to delay image loading and improve page speed.