Image Tag
intermediatePart of HTML Content & Structure
Theory
The <img> element embeds images into a web page. It is a void element — all information is provided through attributes.
Required Attributes
src— the image file path or URL (absolute or relative)alt— alternative text describing the image. This is critical for accessibility (screen readers use it) and appears when the image fails to load
Width and Height
Specifying width and height helps the browser reserve space before the image loads, preventing layout shifts (Cumulative Layout Shift or CLS). Always use the actual image dimensions:
<img src="photo.jpg" alt="Description" width="800" height="600">Responsive Images
For responsive design, use CSS max-width: 100% to make images scale with their container. The srcset attribute provides multiple image sizes for different screen resolutions.
Supported Formats
Common web formats: JPEG (photos), PNG (transparency), GIF (animations), SVG (vectors), and WebP (modern compression).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Images Demo</title>
<style>
img { max-width: 100%; height: auto; border-radius: 8px; }
</style>
</head>
<body>
<h1>My Gallery</h1>
<h2>Mountain Landscape</h2>
<img src="https://via.placeholder.com/600x400" alt="A beautiful mountain landscape with snow-capped peaks" width="600" height="400">
<p>A serene view of the mountains at sunrise.</p>
<h2>City Skyline</h2>
<img src="https://via.placeholder.com/600x400" alt="A city skyline illuminated at night" width="600" height="400">
<p>The city lights create a stunning nighttime panorama.</p>
</body>
</html>Exercises
Create an Image Gallery
Create an HTML page with an h1 heading 'My Gallery' and three images. Each image must have a proper alt attribute, width and height, and a caption paragraph below it.
Expected Output:
A gallery page with three images, each with alt text, width/height attributes, and a descriptive caption beneath.