Skip to main content
Practice

img Tag

The <img> tag is used to insert images into a web page.

The key attributes of the img tag are src, alt, width, and height.


src

This is a mandatory attribute that specifies the URL of the image. The URL can point to an image within the same website or from an external website. Without the src attribute, the <img> tag will not display any image.

img Tag src Attribute
<img src="https://example.com/myimage.jpg" />

alt

This attribute specifies alternative text for the image. It is used as a fallback if the image fails to load, or to provide a description for visually impaired users benefiting from screen readers. It is not mandatory, but it is essential for SEO (Search Engine Optimization).

Setting Alternative Text
<img src="https://picsum.photos/300" alt="A scenic view of the sea at sunset" />

width and height

These attributes define the width and height of the image, with the default unit being pixels (px). Pixels represent individual dots on the screen based on the resolution. If width and height are not specified, the image will be displayed at its original size.

Setting Image Size
<img src="https://picsum.photos/300" width="300" height="200" />

Using the img Tag

  1. Specifying src and alt attributes
Basic Image Tag Usage
<img src="https://picsum.photos/300" alt="Profile Picture" />

  1. Setting image size using width and height
Setting Image Size
<img
src="https://picsum.photos/300"
alt="Random Image"
width="200"
height="150"
/>

Summarizing the img Tag

  • Use the src attribute to specify the URL of the image.

  • The alt attribute provides a description or text to be displayed if the image fails to load.

  • Adjust the size of the image by utilizing the width and height attributes.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.