Working with images in HTML


Reading time: 30 minutes

Snow
Forest
Mountains

Images can be inserted into our HTML page using <img> tag. The <img> tag is an empty tag, which means that it does not have a closing tag. We can insert parameters of the <img> element using various attributes like src, alt, height and width.

Example:

<img src = "image.png" style = "width:40%; height:40%;">

Output:

Attributes of <img> tag


1. "scr" attribute


The src attribute contains the source URL of the image. If the image is present in the current working directory, then we can specify the image name only. For example:

<img src="img1.jpg">

Otherwise, if it's inside any other directory, then it may be specified as:

<img src="folder\img1.jpg">

2. "alt" attribute


The alt attribute provides an alternate text for an image. If the user for some reason cannot view it (because of slow connection or an error in the src attribute) then this alternate text will be displayed. The value of the alt attribute should describe the image.

Example:

<img src="image.jpg" alt="alternate_text">

Output:

alternate_text

3. "width" and "height" attribute


The width and height attribute denotes the height and width of the image. This can be visualised from the code below.

Example:

<img src="image.jpg" alt="text" width="500" height="600">

Alternatively, we can also use the style attribute to specify the image height and width.

Example:

<img src = "image.jpg" alt="text" style = "width: 128px; height: 128px;">



Important Points ⭐


  • If we want to display an image which is present at different server, then we can place the URL in the src attribute.
<img src = "https://www.website.com/image.jpg">
  • We can also use the img tag to display animated images (.gif).
<img src = "programming.gif">
  • If we want to insert an image as a link, then we need to put it within <a> tag. For example:
<a href="abc.html"><img src="image.jpg"></a>

Questions

1. Which attribute is not an attribute of <img> tag?

length
alt
src
width
length is not an attribute of <img> tag.

2. Which attribute provides an alternate text for an image?

alt
alternate
alt_text
None of the options
The alt attribute provides an alternate text for an image.