SmartCodingTips

HTML Image Tag Attributes

The <img> tag in HTML supports several attributes that control how images are displayed and behave on a webpage. Understanding these attributes is key to effective image usage.

1. src (Source)

Specifies the path or URL of the image file to display.


<img src="images/photo.jpg" alt="A beautiful scenery">
            

2. alt (Alternative Text)

Provides descriptive text for the image, shown if the image cannot load and used by screen readers for accessibility.


<img src="logo.png" alt="Company Logo">
            

3. width and height

Defines the displayed width and height of the image in pixels. Using these can help prevent layout shifts while the image loads.


<img src="photo.jpg" alt="Scenery" width="600" height="400">
            

4. title

Provides additional information shown as a tooltip when the user hovers over the image.


<img src="icon.png" alt="Settings" title="Settings Icon">
            

5. loading

Controls lazy loading behavior for images to improve page load speed. Common values:

  • lazy: Defer loading the image until it’s near the viewport.
  • eager: Load the image immediately (default behavior).

<img src="large-photo.jpg" alt="Landscape" loading="lazy">
            

6. srcset and sizes (Responsive Images)

Allow specifying multiple image sources for different screen sizes or resolutions.


<img 
  src="small.jpg" 
  srcset="small.jpg 500w, medium.jpg 1000w, large.jpg 1500w" 
  sizes="(max-width: 600px) 500px, 1000px" 
  alt="Responsive Image">
            

This helps the browser pick the best image version to optimize loading.

7. usemap (Image Maps)

Specifies a reference to an image map defined elsewhere in the document, allowing clickable areas on the image.


<img src="plan.jpg" alt="Floor Plan" usemap="#floorplan">

<map name="floorplan">
  <area shape="rect" coords="34,44,270,350" href="room1.html" alt="Room 1">
</map>
            

Summary of Common Image Attributes

Attribute Purpose Example
src Image source URL <img src="image.jpg">
alt Alternative text for accessibility <img alt="Description">
width Width in pixels <img width="300">
height Height in pixels <img height="200">
title Tooltip text on hover <img title="Info">
loading Lazy loading control <img loading="lazy">
srcset Responsive image sources <img srcset="img1.jpg 500w, img2.jpg 1000w">
usemap Reference image map <img usemap="#mapname">