Skip to main content

Image Tag

In HTML, we use the img tag to embed images within our webpage. This tag does not have a closing tag, unlike most other HTML tags, making it an empty element.

Syntax of the img Tag

Here is the basic syntax of an img tag:

<img src="url" alt="alternative text" width="500" height="600">

Let's break down the attributes:

  • src: This attribute specifies the source URL of the image you want to embed.

  • alt: This attribute provides alternative text for the image. If the image cannot be displayed for any reason (like broken URL or if the viewer has chosen to view websites without images), then this text will be shown instead.

  • width and height: These attributes are used to specify the width and height of the image. The values are specified in pixels.

Using the img Tag

Now, let's see how to use an img tag to display an image on a webpage. Suppose we have an image named "example.jpg" stored in the same folder as our HTML file.

<img src="example.jpg" alt="Example Image">

This will display the image "example.jpg" on the webpage. If the image cannot be displayed, then "Example Image" will be shown instead.

Width and Height Attributes

You can use the width and height attributes to resize the image. Suppose we want to display the same image but with a width of 500 pixels and a height of 300 pixels:

<img src="example.jpg" alt="Example Image" width="500" height="300">

This will display the "example.jpg" image with the specified width and height.

Absolute vs Relative Paths

The src attribute can accept both absolute and relative paths:

  • An absolute path is a full URL to the image:
<img src="http://www.example.com/images/example.jpg" alt="Example Image">
  • A relative path is the path to the image from the current directory:
<img src="images/example.jpg" alt="Example Image">

In this case, the image is located in a subdirectory named "images".

The Importance of the alt Attribute

The alt attribute is critical not just for situations where the image cannot be displayed. It also improves website accessibility, as screen readers for visually impaired users read out this text. It is good practice to include meaningful alt text that describes the image's content or function.

<img src="example.jpg" alt="Pie chart showing sales data">

In HTML, using images effectively can greatly improve your website's look and feel. Practice using the img tag and experiment with different attributes to get a better feel for how it works.