Certified HTML5 Developer Learning Resources img Tag for images

Learning Resources
 

img Tag for images


Using the <img> Tag for Images

The <img> tag is essential for displaying images on a web page. At its core, the tag looks like this:

<img src="image1.jpg" alt="Description of image">


Understanding the Image Tag

Images are not actually part of the HTML file; they are separate files that are embedded into the web page when viewed by a browser. Thus, a simple web page with one image involves two files: the HTML file and the image file itself.


For example, consider the following scenario: both the HTML file and the image file (image1.jpg) are located in the same folder. The HTML file includes an <img> tag that refers to image1.jpg. When the HTML file is opened in a browser, it requests the image file and displays it on the page where the tag is placed.


Key Attribute: src

The most crucial attribute of the <img> tag is src, which stands for "source." It specifies the path to the image file that should be displayed.


Here's a breakdown of the <img> tag attributes:

  • src: Defines the path to the image file. This can be a relative or absolute URL. For example, src="images/photo.jpg" points to an image in a subfolder named images.
  • alt: Provides alternative text for the image if it cannot be displayed. This attribute is important for accessibility and SEO. For example, alt="A beautiful sunset" describes the content of the image.
  • width and height: Define the dimensions of the image. These attributes are optional but can be used to set the size of the image directly in the HTML. For example, width="300" height="200".


Example HTML with an Image Tag

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Image Example</title>

</head>

<body>

    <h1>Welcome to My Website</h1>

    <p>Here is an example of an image displayed on a web page:</p>

    <img src="image1.jpg" alt="A scenic view of mountains" width="500" height="300">

    <p>Above is a beautiful image of mountains.</p>

</body>

</html>


In this example:

  • The <img> tag embeds the image image1.jpg into the web page.
  • The alt attribute describes the image, which improves accessibility for users who use screen readers or if the image fails to load.
  • The width and height attributes control the displayed size of the image on the web page.

By using these attributes, you ensure that the image is correctly displayed and accessible to all users.

 For Support