HTML Image Tag and Attributes

The HTML <img> tag is used to embed images in a webpage. It is a self-closing tag, meaning it does not have a closing </img> tag. The <img> tag has several attributes that define the image source, appearance, and behavior.


Basic Syntax

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

Attributes of <img> Tag

  1. src (Source)

    • Specifies the path to the image file.
    • Can be a relative path (images/photo.jpg) or an absolute URL (https://example.com/photo.jpg).
    • Required attribute.
    <img src="image.jpg" alt="Sample Image">
  2. alt (Alternative Text)

    • Provides a textual description of the image for accessibility.
    • Shown when the image cannot be loaded or viewed.
    • Helps with SEO (search engine optimization).
    • Recommended attribute.
    <img src="image.jpg" alt="A beautiful sunrise">
  3. width and height

    • Define the dimensions of the image.
    • Can use pixels (px) or percentages (%).
    • Helps browsers reserve space for the image during page load.
    <img src="image.jpg" alt="Sample Image" width="300" height="200">
  4. title

    • Provides additional information about the image as a tooltip when hovered over.
    <img src="image.jpg" alt="Sample Image" title="Hover text">
  5. loading

    • Defines how and when the image should be loaded.
      • lazy: Delays loading the image until it’s near the viewport.
      • eager: Loads the image immediately.
    <img src="image.jpg" alt="Sample Image" loading="lazy">
  6. crossorigin

    • Specifies if the image should be loaded with CORS (Cross-Origin Resource Sharing).
      • anonymous: Loads the image without credentials.
      • use-credentials: Loads the image with credentials like cookies.
    <img src="image.jpg" alt="Sample Image" crossorigin="anonymous">
  7. referrerpolicy

    • Controls the referrer information sent when loading the image.
      • Common values: no-referrer, origin, same-origin.
    <img src="image.jpg" alt="Sample Image" referrerpolicy="no-referrer">

Example: Complete <img> Tag

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>HTML Image Example</title>
</head>
<body>
  <h1>HTML Image Example</h1>
  <img
    src="sunrise.jpg"
    alt="A beautiful sunrise over the mountains"
    width="600"
    height="400"
    title="Sunrise Photo"
    loading="lazy"
  >
</body>
</html>

Comments

Popular posts from this blog

Introduction to Computer

History of Computer

Computer Generation