Adding Images Using the <img> Tag


Images are a key component of web design and help make content more engaging. In HTML, the <img> tag is used to insert images into a webpage. The <img> tag is an empty element, meaning it does not have a closing tag. This article will cover how to use the <img> tag, along with attributes that help control the display of images.

Basic Syntax of the <img> Tag

The <img> tag requires at least one attribute, src, which specifies the path to the image file. Another important attribute is alt, which provides alternative text for the image. The basic syntax for the <img> tag is:

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

Example of Adding an Image

Here is an example of adding a simple image to a webpage:

    <img src="https://example.com/path/to/image.jpg" alt="Example Image">
        

In this example, src specifies the URL of the image, and alt provides a description that will appear if the image cannot be displayed.

Attributes of the <img> Tag

The <img> tag has several attributes that control how the image is displayed:

  • src: Specifies the image source (path or URL).
  • alt: Provides alternative text for the image.
  • width: Sets the width of the image (in pixels or percentage).
  • height: Sets the height of the image (in pixels or percentage).
  • title: Adds a tooltip that appears when the user hovers over the image.

Example of an Image with Width and Height

You can set the width and height of an image using the width and height attributes:

    <img src="https://example.com/path/to/image.jpg" alt="Example Image" width="300" height="200">
        

In this example, the image will be displayed at 300 pixels wide and 200 pixels tall.

Using the Title Attribute

The title attribute adds a tooltip that appears when the user hovers over the image:

    <img src="https://example.com/path/to/image.jpg" alt="Example Image" title="Hover text for the image">
        

In this case, when the user hovers over the image, they will see the tooltip "Hover text for the image."

Using Local and External Image Sources

The src attribute can point to a local image file or an external URL.

Local Image Example

    <img src="images/photo.jpg" alt="Local Photo">
        

This example assumes the image file photo.jpg is located in an "images" folder in the same directory as the HTML file.

External Image Example

    <img src="https://example.com/image.jpg" alt="External Image">
        

This example uses an external URL to load an image from another website.

Conclusion

The <img> tag in HTML is a simple yet powerful tool for adding images to a webpage. By using attributes like src, alt, width, height, and title, you can control how images are displayed and improve the accessibility of your website. Images are an essential part of web design, and understanding how to use the <img> tag will help enhance the visual appeal of your webpages.





Advertisement