Skip to main content

What does the <img> element do in HTML?

The <img> element is used to insert an image into a web page. It has no closing tag and loads the picture via a link from the internet or from the site's files.


1. Simplest example

html
<img src="cat.jpg" alt="Cat on the windowsill">

What's happening here:

  • src - the path to the image file (short for "source");
  • alt - alternative text shown if the image fails to load (or read aloud by a screen reader).

The browser will load and display the file cat.jpg right on the page.


2. Main attributes of <img>

AttributePurposeExample
srcPath to the image (required)src="images/photo.png"
altDescription text shown if the image does not displayalt="Profile photo"
widthImage width (in pixels or %)width="200"
heightImage heightheight="150"
titleTooltip shown on hovertitle="Click to enlarge"
loadingLoading optimization (lazy, eager)loading="lazy"

3. Image paths

Relative path (if the file is in the project folder):

html
<img src="img/pic.jpg" alt="Photo">

Absolute path (if the picture is from another site):

html
<img src="https://example.com/image.jpg" alt="Photo">

4. Example with dimensions and description

html
<img src="mountains.jpg" alt="Mountains at dawn" width="400" height="250">

The image will be displayed at the specified dimensions (400x250 pixels).


5. The alt attribute: why it matters

  • displayed if the picture fails to load;
  • used by search engines (SEO);
  • helps people with visual impairments (screen readers read the alt text).

Example:

html
<img src="avatar.png" alt="User photo">

If the file is not found, the browser will show:

javascript
User photo

6. The loading="lazy" attribute

Modern browsers can defer loading images that are not yet visible on the screen:

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

This speeds up page loading.


html
<a href="https://example.com"> <img src="logo.png" alt="Company logo"> </a>

The image becomes a clickable link.


Summary:

PropertyDescription
Tag<img> (non-paired)
PurposeInserting an image
Required attributessrc, alt
Commonly usedwidth, height, title, loading
FeaturesContains no text, has no closing tag

In simple terms: <img> is a "window" for a picture on a site. src says where the image is located, and alt - what should be there if it fails to load.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.