HTML Images

Images make a page more interesting. In HTML an image is added with the <img> tag. It is an empty element, so it has no closing tag.

<img src="photo.jpg" alt="A boy playing cricket" width="300" height="200">

Attributes of the img tag

AttributeMeaning
srcRequired. The path or URL of the image file
altRequired. Alternative text, shown if the image fails to load and read aloud by screen readers
width, heightSize in pixels. Giving both stops the page from jumping while the image loads
titleTooltip on mouse hover
loading="lazy"Load the image only when the visitor scrolls near it

Image path

<img src="logo.png" alt="Logo">
<img src="images/logo.png" alt="Logo">
<img src="../images/logo.png" alt="Logo">
<img src="https://www.example.com/logo.png" alt="Logo">
  • The first image is in the same folder as the HTML file.
  • The second one is inside an images folder.
  • ../ goes one folder up.
  • The last one is on another website. Try to host your own images, because the other site may remove them.

Write a good alt text

  • Describe what the image shows, in a short sentence: “Red bicycle near a wall”.
  • Do not start with “image of” or “picture of”.
  • For a purely decorative image use an empty alt: alt="".

Image formats

FormatBest for
JPG / JPEGPhotos
PNGLogos, screenshots, images with transparent background
GIFSmall simple animations
SVGIcons and logos that must stay sharp at any size
WebPModern format, smaller files than JPG and PNG

Image with a caption

<figure>
  <img src="photo.jpg" alt="A mountain view" width="300">
  <figcaption>A view of the mountains in the morning.</figcaption>
</figure>

Responsive image

To make an image shrink on small screens, use a bit of CSS.

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

Summary

  • Use <img src="..." alt="...">.
  • Always write an alt text, and set width and height.
  • Use JPG for photos, PNG for logos and SVG for icons.
  • Next: HTML Lists.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write an HTML program to create links (new tab and email)
Write an HTML program to display an image
Interview Questions & Answers
How do you create links to sections within the same page?
What do you mean by HTML links?
How to create a link to jump to a specific part of a page in HTML?
How do you insert an image into HTML?
What is the alt attribute in HTML and why is it important?
How to open a link in a new tab in HTML?
What is the difference between absolute and relative URL in HTML?