Images in HTML

HTML <img> tag is used to display image on the web page.

HTML <img> tag is an empty tag that contains attributes only. Closing tags are not used in HTML image element.

Why use images in webpages?

Images can improve the design and the appearance of a web page.

The <img> tag has two required attributes:

  • src – Specifies the path to the image
  • alt – Specifies an alternate text for the image

Example of HTML image

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of HTML image</title>
</head>

<body>
    <h2>HTML Image Example</h2>
    <img src="https://eywiah.com/wp-content/uploads/2021/12/image-1024x995.png" alt="Good Morning Friends" />
</body>

</html>

Attributes of HTML <img> tag

1) src

It is a necessary attribute that describes the source or path of the image. It instructs the browser where to look for the image on the server.

The broken link icon and the alt text are shown if the browser cannot find the image.

The required src attribute specifies the path (URL) to the image.

The location of image may be on the same directory or another server.

2) alt

The alt attribute defines an alternate text for the image, if it can’t be displayed because of slow connection or an error in the src attribute.

The value of the alt attribute describe the image in words. The alt attribute is considered good for SEO prospective. The value of the alt attribute should describe the image.

Remember if a browser cannot find an image, it will display the value of the alt attribute.

3) width and height

The width and height attributes always define the width and height of the image in pixels.

The width and height attributes are not recommended now. You should apply CSS in place of these attributes.

Always try to insert the image with height and width, else it may flicker while displaying on webpage.

Use of alt, height and width attribute with <img> tag example

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of HTML image</title>
</head>

<body>
    <h2>HTML Image Example</h2>
    <img src="https://eywiah.com/wp-content/uploads/2021/12/image-1024x995.png" alt="Good Morning Friends" height="180" width="300"/>
</body>

</html>