image element in HTML

img element is used to add an image in HTML document. <img> tag is non-closing tag. That means, it does not have closing tag. let us have a look at example.

a circle drawn on a blackboard

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <img src="../../assetsfiles/img/html/basic/home-banner-1.jpg" alt="a circle drawn on a blackboard" />
    </body>
</html>
                        

In above example, <img> tag has two attributes.

  • src

    This attribute is a relative path to the image. Remember, this is the relative path from the HTML page, in which the image is added.
    In the above example, '..' means go to the parent folder and '.' means current folder.

  • alt

    alt tag provides the name of the image when the image cannot be loaded like when internet breaks or path of the image is changed or image does not exist. At that time, alt describe the image. alt should be used because it helps great in SEO.

height & width

height and width attributes of img are used to provide height and width of the image. You can use pixels or percentage ( of parent's size ).

a circle drawn on a blackboard

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <img width="100" height="100" src="../../assetsfiles/img/html/basic/home-banner-1.jpg" alt="a circle drawn on a blackboard" />
    </body>
</html>
                        

In above example, we have givent width="100" that means, 100px. Alternatively, you can provide width="100px" is also the same.
width="100%" means same width of the parent.

srcset

We use low-resolution images to load it faster, so our page loads faster but images may look blur in high-resolution devices.
So for that problem, srcset attribute is used. it contains the reference to high resolution images. So in high resolution devices will use srcset image instead of src image.

a circle drawn on a blackboard

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <img src="../../assetsfiles/img/html/basic/home-banner-1.jpg" srcset="../../assetsfiles/img/html/basic/home-banner-hd.jpg 2x" alt="a circle drawn on a blackboard" />
    </body>
</html>
                        

Deprecated Attributes

There are some attributes which are not supported anymore. These attributes may work but are not supported. Here is the list.

  • align
  • border
  • hspace
  • longdesc
  • name
  • vspace

Conclusion

We have learned about img element and its attributes.
In next section, we will learn about tables in HTML.