5.1 Images (img)

5.1 Images (img)
Table of Contents

The <img> element in HTML is used to embed images in a webpage. It is an empty element, meaning it does not have a closing tag and contains attributes that provide the source of the image, alternative text, dimensions, and other properties.

Basic Usage of <img>

The <img> element requires at least one attribute: src, which specifies the path to the image file.

Example:

<img src="path/to/image.jpg" alt="Description of image">

In this example, "path/to/image.jpg" is the path to the image file, and "Description of image" provides alternative text that describes the image.

Attributes of <img>

  • src: Specifies the URL of the image.
  • alt: Provides alternative text for the image, which is displayed if the image cannot be loaded. It is also used by screen readers for accessibility.
  • width and height: Define the dimensions of the image in pixels.
  • title: Provides additional information about the image, often displayed as a tooltip when the mouse hovers over the image.
  • loading: Specifies the loading behavior of the image. It can have values like "lazy" to defer loading until the image is near the viewport.

Example with Attributes:

<img src="path/to/image.jpg" alt="Description of image" width="300" height="200" title="Image Tooltip" loading="lazy">

In this example, the image is given specific dimensions, a tooltip, and a lazy loading behavior.

Responsive Images

To make images responsive, you can use CSS or HTML attributes to ensure that the images adjust their size based on the viewport.

Example:

<img src="path/to/image.jpg" alt="Description of image" style="max-width: 100%; height: auto;">

In this example, the image scales according to the width of its container, maintaining its aspect ratio.

Fun Question:

If you could place any image on a webpage, what would it be and why? Share your favorite images and reasons!

Summary

The <img> element is essential for embedding images in HTML. By using attributes like src, alt, width, height, title, and loading, you can control the appearance, accessibility, and loading behavior of images, ensuring they enhance the content and user experience on your website.

I am a passionate writer. Read more.

Post a Comment

Don't spam links or promote stuff in the comments. It's annoying and lowers the conversation quality. Contribute respectfully and helpfully instead.