HTML Docs

HTML Images

A guide to understanding how to use HTML images, including attributes like src, alt, title, width, height, lazy loading, and supported image formats.

In this guide, we'll cover how to use HTML images effectively, including common attributes and techniques like lazy loading and supported image formats.

Images are essential to enrich the content of your webpage. In HTML, the <img> tag is used to display images.

The <img> tag doesn't have a closing tag, and it's self-closing.

Example:

<img src="image.jpg" alt="Description of the image">

🖼️ Important Attributes for <img>

  • src: The source attribute, used to specify the path to the image.
  • alt: The alt text provides a description of the image. It is essential for accessibility and appears if the image cannot be loaded.
  • title: Provides additional information when the user hovers over the image.
  • width and height: Specifies the width and height of the image (in pixels).

Example:

<img src="example.jpg" alt="An example image" title="Hover text" width="300" height="200">

🛏️ Lazy Loading

Lazy loading is a technique that defers the loading of images until they are required (i.e., when they are about to enter the viewport). This improves the page's load time.

Example (using the loading="lazy" attribute):

<img src="large-image.jpg" alt="Lazy Loaded Image" loading="lazy">

This will load the image only when it is about to appear on the user's screen.

🖼️ Supported Image Formats

Different image formats are used for different purposes based on the required quality, file size, and browser compatibility. Below are some common image formats used in HTML:

  • JPG: A widely used format for high-quality images with relatively small file sizes. Ideal for photographs.
  • PNG: Supports transparent backgrounds and is ideal for graphics and logos.
  • SVG: Scalable vector graphics, perfect for images that need to scale without losing quality, like logos or icons.
  • WebP: A modern image format that provides superior compression and quality. It's supported in most modern browsers.

Example for different formats:

<!-- JPG Image -->
<img src="image.jpg" alt="JPG Image">
 
<!-- PNG Image -->
<img src="image.png" alt="PNG Image">
 
<!-- SVG Image -->
<img src="logo.svg" alt="SVG Logo">
 
<!-- WebP Image -->
<img src="image.webp" alt="WebP Image">

🧪 Try Yourself

import "./styles.css";

document.getElementById("app").innerHTML = `
<h1>Hello world</h1>
`;

✅ Conclusion

In this guide, we have covered the basic usage of the <img> tag, including how to define essential attributes like src, alt, width, height, and title. We've also discussed lazy loading, which optimizes page performance, and explored various image formats such as JPG, PNG, SVG, and WebP.

💡 Pro Tip: Always add alt text to your images for accessibility. It helps screen readers describe images to users with visual impairments.

🔗 Resources

On this page