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
No Content Found.
Interview Questions & Answers
No Content Found.