The HTML <img> tag is used to insert images into an HTML document. It allows you to display images on your web page, whether they are stored locally or hosted on a remote server.
Here's the basic structure of the <img> tag:
<img src="image-source" alt="alternative-text">
The src attribute specifies the source or location of the image. It can be a relative path (e.g., "images/my-image.jpg") or an absolute URL (e.g., "https://www.example.com/images/my-image.jpg").
The alt attribute provides alternative text for the image. It is displayed when the image cannot be loaded or for accessibility purposes. The text should describe the content or purpose of the image.
Example usage:
<img src="images/my-image.jpg" alt="A beautiful sunset">
In this example, the <img> tag is used to display an image named "my-image.jpg" located in the "images" directory relative to the HTML file. The alternative text "A beautiful sunset" will be displayed if the image cannot be loaded or for users who rely on screen readers.
Additionally, the <img> tag supports several attributes that provide additional control and functionality:
width and height: Specifies the dimensions of the image in pixels. It is recommended to specify these attributes to avoid page reflow when the image is loaded.
title: Provides a tooltip or additional information about the image when the user hovers over it.
loading: Determines how the image should be loaded, such as "lazy" to defer loading until it is visible in the viewport.
Example usage with additional attributes:
<img src="images/my-image.jpg" alt="A beautiful sunset" width="800" height="600" title="Sunset at the beach" loading="lazy">
The <img> tag is widely used for incorporating visual content into web pages, including photographs, illustrations, icons, and more. It is essential to optimize image sizes, use appropriate alternative text, and ensure responsive design for different devices to enhance the user experience.
Remember to provide descriptive alternative text for images to ensure accessibility and improve the understanding of the content for users who cannot see the images.