Images make websites more attractive, informative, and engaging.
In HTML, images are added using the <img> tag.
Unlike most HTML elements, the <img> tag is a self-closing tag.
It does not have a closing tag.
Basic Syntax of the <img> Tag
<img src="image.jpg" alt="Description of image">
Explanation:
AttributeMeaningsrcSpecifies the path (URL) of the imagealtAlternative text if image cannot loadwidthImage widthheightImage height
The src Attribute
The src (source) attribute tells the browser where to find the image.
It can be:
1️⃣ Local Image (same folder)
<img src="photo.jpg" alt="My Photo">
2️⃣ Image inside a folder
<img src="images/photo.jpg" alt="My Photo">
3️⃣ Online Image (URL)
<img src="https://via.placeholder.com/150" alt="Placeholder Image">
The alt Attribute (Very Important)
The alt attribute provides alternative text.
It is important for:
Example:
<img src="car.jpg" alt="Red sports car parked on the road">
Always describe the image clearly.
Setting Image Size
You can control image size using:
Method 1: HTML Attributes
<img src="photo.jpg" alt="Photo" width="300" height="200">
Method 2: CSS (Recommended)
<img src="photo.jpg" alt="Photo" style="width:300px; height:200px;">
Best Practice: Use CSS instead of HTML width/height attributes in modern development.
Image as a Link
You can make an image clickable by placing it inside an <a> tag.
<a href="https://example.com">
<img src="photo.jpg" alt="Clickable Image">
</a>
Image Title Attribute
You can add extra information using the title attribute.
<img src="photo.jpg" alt="Beach" title="Beautiful beach view">
When you hover over the image, the title appears.
Image Formats Supported in HTML
Common image formats:
💡 Modern websites prefer WebP because it loads faster.
Best Practices for Using Images
✅ Always include alt text
✅ Optimize images to reduce file size
✅ Use correct image format
✅ Use CSS for styling
✅ Avoid very large images (slow loading)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML Images Practice</title>
</head>
<body>
<h1>HTML Image Example</h1>
<a href="https://example.com" target="_blank">
<img
src="https://via.placeholder.com/300x200"
alt="Sample placeholder image"
title="Click to visit example website"
width="300"
height="200">
</a>
<p>This image is clickable and opens in a new tab.</p>
</body>
</html>