How to Add an Image in HTML: A Step-by-Step Guide

The Basics of Adding Images in HTML

In HTML, images are added using the <img> tag. This tag is self-closing, meaning it does not require a closing tag.

Basic Syntax of the img Tag

The <img> tag requires the following attributes:

AttributeDescriptionRequired
srcSpecifies the path to the image fileYes
altProvides alternative text for the imageYes
width/heightOptional attributes to define image dimensionsNo

Example:

<img src="example.jpg" alt="Description of the image" width="500">

Adding Images with Different File Paths

a. Local File

Use a relative path if the image is in the same directory as the HTML file.

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

b. Subfolder

If the image is in a subfolder, specify the folder name in the path.

<img src="images/photo.jpg" alt="Subfolder image">

c. Absolute URL

Use the full URL for images hosted on external servers.

<img src="https://example.com/image.jpg" alt="Remote image">

4. Responsive Images

To make images responsive (adjustable based on screen size), use CSS or set the width attribute to 100%.

Example:

<img src="example.jpg" alt="Responsive image" style="max-width: 100%; height: auto;">

Best Practices for Adding Images

Always Include alt Text:

Always Include alt Text:

Describe the image for accessibility and SEO.

Use meaningful text (e.g., “Golden Retriever puppy playing in the park”).

Optimize Image Size:

Use tools to compress images without losing quality to improve page load times.

Common tools: TinyPNG, ImageOptim.

Use Modern Formats:

Consider using formats like WebP for faster loading and smaller file sizes.

Lazy Loading:

  • Defer loading images outside the viewport to improve performance.
<img src="image.jpg" alt="Lazy loaded image" loading="lazy">

Adding a Clickable Image

You can wrap the <img> tag inside an <a> tag to make the image clickable.

Example:

<a href="https://example.com">
    <img src="example.jpg" alt="Clickable image" width="300">
</a>

Using Decorative Images

If the image is purely decorative, you can leave the alt attribute empty. Avoid this for informative images.

Example:

<img src="decorative.jpg" alt="" role="presentation">

Example: Full HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Adding an Image</title>
</head>
<body>
    <h1>Welcome to My Website</h1>
    <p>Here is an image of a sunset:</p>
    <img src="sunset.jpg" alt="Beautiful sunset over the mountains" width="600" loading="lazy">
</body>
</html>

HTML img

Quiz: Test Your Knowledge