HTML <img> Tag โ Display Images
๐ Introduction
The <img> tag is used to display images in a webpage.
It is a self-closing tag, meaning it does not need a closing tag.
Images are essential for:
- Websites
- Blogs
- Portfolios
- UI design
๐งฑ Syntax
<img src="image.jpg" alt="description" />
๐ก Example
<!DOCTYPE html>
<html>
<head>
<title>Image Example</title>
</head>
<body>
<h1>My Image</h1>
<img src="cat.jpg" alt="A cute cat" />
</body>
</html>
๐ฅ๏ธ Output Explanation
- The browser loads the image from
src - If the image fails to load,
alttext is shown - The image appears inline in the page
๐ฏ Important Attributes
1. src (Source)
Defines the image file path.
<img src="photo.png" />
โ Can be:
- Local file (
images/pic.jpg) - Online URL (
https://example.com/img.jpg)
2. alt (Alternative Text)
<img src="car.jpg" alt="Red sports car" />
โ Shows text if image fails โ Helps accessibility (screen readers) โ Important for SEO
๐ Controlling Image Size
Method 1: HTML attributes
<img src="image.jpg" width="300" height="200" />
Method 2: CSS (recommended)
<img src="image.jpg" style="width:300px;" />
๐ฏ When to Use <img>
Use it for:
- Profile pictures
- Product images
- Banners
- Blog visuals
- Icons
โ ๏ธ Important Rules
- Always include
altattribute - Use correct file paths
- Avoid large images without optimization
๐ซ Common Mistakes
- Missing
altโ - Wrong image path โ
- Using images without optimization โ
๐จ Example with Styling
<img src="cat.jpg" alt="Cat" style="width:200px; border-radius:10px;" />
๐งช Mini Exercise
Create a page with:
A heading
One image from your computer or online
Another image with:
- Custom width
- Rounded corners
Proper
alttext for both