2.4: Images & Media
Add images to your web pages using proper HTML markup, alt text for accessibility, and responsive image techniques. Learn to optimize images for web performance.
1. The Image Element (<img>)
Basic Image Syntax
<img src="image.jpg" alt="Description of image">
Required attributes:
src- Source (path to image file)alt- Alternative text (description for accessibility)
Complete Image Example
<img
src="/images/sunset.jpg"
alt="Orange sunset over calm ocean with silhouetted palm trees"
width="800"
height="600"
loading="lazy"
>
Attributes:
src- Image file pathalt- Text descriptionwidth- Intrinsic width in pixelsheight- Intrinsic height in pixelsloading-lazyoreager(performance optimization)
2. Image Paths
Relative Paths
<img src="photo.jpg" alt="Photo">
<img src="images/photo.jpg" alt="Photo">
<img src="../images/photo.jpg" alt="Photo">
<img src="/assets/images/photo.jpg" alt="Photo">
Absolute URLs
<img src="https://example.com/images/photo.jpg" alt="Photo">
<img src="https://cdn.example.com/images/photo.jpg" alt="Photo">
Best practice: Use root-relative paths (/images/photo.jpg) for internal images
3. Alt Text (Alternative Text)
Alt text is critical for accessibility and SEO.
When Image Conveys Information
<img src="chart.png" alt="Bar chart showing 50% increase in sales from 2023 to 2024">
<img src="product.jpg" alt="Red leather backpack with front zipper pocket">
<img src="diagram.png" alt="Flowchart: User login process with authentication steps">
When Image is Decorative
<img src="decorative-pattern.png" alt="">
<img src="divider-line.png" alt="">
Note: Use alt="" (empty) for purely decorative images, but still include the attribute
When Image is a Link
<a href="/home">
<img src="logo.png" alt="Company Name Home">
</a>
<a href="/products/laptop">
<img src="laptop-thumb.jpg" alt="View MacBook Pro details">
</a>
Complex Images (Charts, Graphs)
<figure>
<img src="complex-chart.png" alt="Sales data for 2024, detailed description below">
<figcaption>
<p>Sales increased 45% in Q1, 30% in Q2, decreased 10% in Q3, and increased 55% in Q4.</p>
</figcaption>
</figure>
<img src="diagram.png" alt="System architecture" aria-describedby="diagram-desc">
<p id="diagram-desc">
The system consists of a frontend React application communicating via REST API
with a Node.js backend, which connects to a PostgreSQL database.
</p>
Alt Text Best Practices
✅ Good alt text:
<img src="dog.jpg" alt="Golden retriever puppy playing with red ball in grassy backyard">
<img src="error-icon.png" alt="Error: Invalid email format">
<img src="step1.png" alt="Step 1: Click the blue 'Sign Up' button in top right">
❌ Bad alt text:
<img src="dog.jpg" alt="Image">
<img src="dog.jpg" alt="DSC_1234.jpg">
<img src="dog.jpg" alt="A dog playing">
<img src="dog.jpg">
Guidelines:
- Be specific and concise
- Don't start with "Image of..." or "Picture of..."
- Convey the purpose, not just appearance
- Keep under 125 characters when possible
- Never omit the
altattribute
4. Image Formats
JPEG (.jpg, .jpeg)
Best for: Photographs, complex images with many colors
Characteristics:
- Small file sizes with lossy compression
- Millions of colors
- No transparency
- Quality degrades with editing/resaving
<img src="photograph.jpg" alt="Mountain landscape at sunrise">
When to use:
- Photos
- Images with gradients
- Complex color compositions
PNG (.png)
Best for: Graphics, logos, images needing transparency
Characteristics:
- Lossless compression
- Supports transparency (alpha channel)
- Great for graphics and text
- Larger file sizes than JPEG
<img src="logo.png" alt="Company logo">
When to use:
- Logos and icons
- Images with transparency
- Screenshots with text
- Simple graphics
WebP
Best for: Modern browsers, all-purpose
Characteristics:
- Superior compression (smaller than JPEG and PNG)
- Supports transparency
- Supports animation
- Both lossy and lossless modes
- Not supported in very old browsers (use fallback)
Example: A picture element with WebP format and JPEG fallback - the picture element contains source elements for modern browsers (WebP) and an img fallback for older browsers.
When to use:
- Modern web projects
- When performance matters
- As primary format with JPEG/PNG fallback
SVG (Scalable Vector Graphics)
Best for: Icons, logos, illustrations
Characteristics:
- Infinitely scalable (no quality loss)
- Very small file sizes
- Editable with code
- Animatable with CSS/JavaScript
- Not good for photographs
<svg width="100" height="100" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" fill="#ff0000"/>
</svg>
<img src="icon.svg" alt="Search icon">
When to use:
- Icons and logos
- Simple illustrations
- Diagrams and charts
- When you need perfect scaling
GIF
Best for: Simple animations
Characteristics:
- Supports animation
- Transparency (limited)
- Only 256 colors
- Large file sizes for animations
<img src="loading-spinner.gif" alt="Loading indicator">
Modern alternative: Use video for animations (smaller file size)
Format Comparison Table
| Format | Use Case | Transparency | Animation | File Size |
|---|---|---|---|---|
| JPEG | Photos | No | No | Small |
| PNG | Graphics/Logos | Yes | No | Medium-Large |
| WebP | All-purpose | Yes | Yes | Very Small |
| SVG | Vectors/Icons | Yes | Yes (CSS/JS) | Tiny |
| GIF | Simple Animation | Limited | Yes | Large |
5. Image Dimensions
Width and Height Attributes
Always specify dimensions to prevent layout shift:
<img src="photo.jpg" alt="Photo" width="800" height="600">
<img src="photo.jpg" alt="Photo">
How it works:
- Browser reserves space based on
widthandheight - Page layout stable while images load
- Better Core Web Vitals (CLS score)
Responsive Images with CSS
<img
src="photo.jpg"
alt="Photo"
width="1200"
height="800"
style="max-width: 100%; height: auto;"
>
CSS for responsive images:
img {
max-width: 100%;
height: auto;
display: block;
}
Aspect ratio preservation:
- Set
widthandheightattributes - CSS:
height: autopreserves aspect ratio max-width: 100%prevents overflow
6. Responsive Images (srcset and sizes)
Problem: One Size Doesn't Fit All
Mobile phone (375px wide) downloads 3000px image = wasted bandwidth
Desktop (1920px wide) displays 800px image = poor quality
Solution: srcset Attribute
Provide multiple image sizes and let browser choose:
<img
src="image-800.jpg"
srcset="
image-400.jpg 400w,
image-800.jpg 800w,
image-1200.jpg 1200w,
image-1600.jpg 1600w
"
sizes="(max-width: 600px) 400px,
(max-width: 1000px) 800px,
1200px"
alt="Responsive image"
width="1200"
height="800"
>
Breakdown:
srcset - Available image sources with widths:
srcset="
image-400.jpg 400w, ← 400 pixels wide
image-800.jpg 800w, ← 800 pixels wide
image-1200.jpg 1200w ← 1200 pixels wide
"
sizes - Display size at different breakpoints:
sizes="
(max-width: 600px) 400px, ← On screens ≤600px, image displays at 400px
(max-width: 1000px) 800px, ← On screens ≤1000px, image displays at 800px
1200px ← Default size
"
Browser logic:
- Check viewport width
- Match against
sizesconditions - Select appropriate image from
srcset - Download only that one image
Pixel Density Descriptors
<img
src="image.jpg"
srcset="
image.jpg 1x,
image-2x.jpg 2x,
image-3x.jpg 3x
"
alt="High-resolution image"
>
Usage:
1x- Standard displays2x- Retina displays (MacBook, iPhone, etc.)3x- Ultra high-DPI displays
Practical Example
<img
src="logo-400.png"
srcset="
logo-200.png 200w,
logo-400.png 400w,
logo-800.png 800w
"
sizes="(max-width: 600px) 200px,
(max-width: 1200px) 400px,
800px"
alt="Company logo"
width="800"
height="200"
>
7. The <picture> Element
Use <picture> for art direction (different images for different screens):
Basic Picture Example
Example: A responsive picture element that serves different images based on screen size - wide image for desktops (1000px+), medium image for tablets (600px+), and small image for mobile devices.
How it works:
- Browser checks
<source>elements in order - First matching
mediaquery wins - If none match, uses
<img>as fallback
Art Direction Example
Example: A picture element for art direction - shows a wide banner for desktop, cropped banner for tablet, and mobile-optimized banner for phones, all with different aspect ratios and focal points.
Modern Format with Fallback
Example: Picture element for format fallback - serves WebP to modern browsers for better compression, with JPEG fallback for browsers that don't support WebP.
Complex Example (Format + Resolution + Art Direction)
Example: Advanced picture element combining format selection, device pixel ratio, and art direction - serves WebP/JPEG in 1x/2x resolutions for desktop, WebP/JPEG for tablet, and mobile fallback image.
8. Figures and Captions
The <figure> Element
Use <figure> for self-contained content (images, diagrams, code):
<figure>
<img src="chart.png" alt="Annual sales growth chart">
<figcaption>Figure 1: Annual sales increased 45% from 2023 to 2024</figcaption>
</figure>
Multiple Images in Figure
<figure>
<img src="photo1.jpg" alt="Mountain view">
<img src="photo2.jpg" alt="Forest trail">
<img src="photo3.jpg" alt="Lake reflection">
<figcaption>Photo gallery: Hiking trip in Rocky Mountains, June 2024</figcaption>
</figure>
Code Listing in Figure
<figure>
<figcaption>Listing 1: Hello World in Python</figcaption>
<pre><code>
def hello():
print("Hello, World!")
hello()
</code></pre>
</figure>
Styling Figures
figure {
margin: 2rem 0;
padding: 1rem;
background: #f5f5f5;
border: 1px solid #ddd;
border-radius: 8px;
}
figure img {
max-width: 100%;
height: auto;
display: block;
}
figcaption {
margin-top: 0.5rem;
font-size: 0.9rem;
color: #666;
font-style: italic;
text-align: center;
}
9. Image Optimization
File Size Optimization
Tools:
- TinyPNG - PNG/JPEG compression
- Squoosh - Web-based image optimizer
- ImageOptim - Mac app
- SVGOMG - SVG optimizer
Guidelines:
- Compress images before uploading
- Use appropriate format (JPEG for photos, PNG for graphics)
- Consider WebP for modern browsers
- Remove metadata (EXIF data)
Resolution Guidelines
| Use Case | Recommended Width | Example |
|---|---|---|
| Thumbnail | 150-300px | Product grid |
| Medium | 600-800px | Blog post |
| Large | 1200-1600px | Hero images |
| Full-width | 1920-2560px | Backgrounds |
Don't serve 4000px images for 400px display
Lazy Loading
Defer loading off-screen images:
<img src="image.jpg" alt="Description" loading="lazy">
<img src="hero.jpg" alt="Hero" loading="eager">
When to use:
loading="lazy"- Below-the-fold images (not visible initially)loading="eager"- Above-the-fold images (critical content)- Omit attribute - Default behavior (usually eager)
Example: Optimized Image Gallery
<img src="hero.jpg" alt="Hero banner" width="1920" height="800" loading="eager">
<img src="gallery-1.jpg" alt="Gallery image 1" width="400" height="300" loading="lazy">
<img src="gallery-2.jpg" alt="Gallery image 2" width="400" height="300" loading="lazy">
<img src="gallery-3.jpg" alt="Gallery image 3" width="400" height="300" loading="lazy">
10. Video and Audio
The <video> Element
Example: A video element with multiple source formats (MP4 and WebM) for browser compatibility, controls for play/pause, and fallback text for unsupported browsers.
Attributes:
controls- Show play/pause controlsautoplay- Auto-play video (use sparingly)loop- Loop videomuted- Start muted (required for autoplay in most browsers)poster- Thumbnail image before playwidth,height- Dimensions
Video with Poster and Controls
Example: Video element with poster image (thumbnail shown before play), controls, dimensions, metadata preloading, multiple formats, and subtitle track for accessibility.
preload values:
none- Don't preload anythingmetadata- Preload metadata only (duration, dimensions)auto- Browser decides (usually preloads some data)
Autoplay Background Video
Example: Background video that autoplays, loops continuously, is muted (required for autoplay), plays inline on mobile, with poster image and multiple formats.
Note: muted required for autoplay in most browsers
The <audio> Element
Example: Audio element with controls, multiple source formats (MP3 and OGG) for browser compatibility, and fallback download link for unsupported browsers.
With additional attributes:
Example: Audio element with controls, metadata preloading, multiple formats, and caption track for accessibility.
Embedding YouTube/Vimeo Videos
<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/VIDEO_ID"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
<div class="video-wrapper">
<iframe src="https://www.youtube.com/embed/VIDEO_ID" ...></iframe>
</div>
<style>
.video-wrapper {
position: relative;
padding-bottom: 56.25%; /* 16:9 aspect ratio */
height: 0;
overflow: hidden;
}
.video-wrapper iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: 0;
}
</style>
11. Complete Examples
Optimized Hero Image
Example: Fully optimized hero image using picture element with:
- Large format for desktop (1200px and up)
- Medium format for tablet (768px and up)
- Small format and fallback on mobile
- Eager loading for above-the-fold content
- Proper alt text and dimensions
Product Gallery with Lazy Loading
<section class="product-gallery">
<h2>Product Images</h2>
<figure>
<img
src="product-main.jpg"
alt="Blue wireless headphones front view"
width="800"
height="800"
loading="eager"
>
<figcaption>Main product image</figcaption>
</figure>
<figure>
<img
src="product-side.jpg"
alt="Blue wireless headphones side profile"
width="800"
height="800"
loading="lazy"
>
<figcaption>Side view</figcaption>
</figure>
<figure>
<img
src="product-detail.jpg"
alt="Close-up of headphone ear cushion and controls"
width="800"
height="800"
loading="lazy"
>
<figcaption>Detail view</figcaption>
</figure>
</section>
12. Practical Exercises
Exercise 2.4.1: Basic Images
Create an HTML page with:
- Three images using different formats (JPEG, PNG, SVG)
- Proper alt text for each image
- Width and height attributes
- One decorative image with empty alt
Exercise 2.4.2: Responsive Images
Implement responsive images using:
- Create three versions of an image (400px, 800px, 1200px)
- Use
srcsetandsizesattributes - Test in browser DevTools (Network tab) at different viewport sizes
Exercise 2.4.3: Picture Element
Create a <picture> element with:
- WebP format for modern browsers
- JPEG fallback for older browsers
- Different crops for mobile, tablet, and desktop
- Proper alt text
Exercise 2.4.4: Media Gallery
Build a complete media gallery with:
- Figures with captions
- Lazy loading for all images except the first
- One embedded video with controls
- Responsive layout (CSS Grid or Flexbox)
13. Knowledge Check
Question 1: Why is the alt attribute required for images?
Show answer
For accessibility. Screen readers use alt text to describe images to visually impaired users. It also helps SEO and displays if the image fails to load.Question 2: When should you use an empty alt attribute (alt="")?
Show answer
For purely decorative images that don't convey information. The `alt` attribute must still be present, but empty, so screen readers skip the image.Question 3: What's the difference between srcset and <picture>?
Show answer
`srcset` provides different resolutions of the same image (browser chooses based on viewport/DPR). `Question 4: Why should you always include width and height attributes?
Show answer
To prevent layout shift (CLS). The browser reserves space for the image before it loads, keeping the layout stable and improving Core Web Vitals scores.Question 5: When should you use loading="lazy"?
Show answer
For below-the-fold images (not visible on initial page load). This defers loading until the user scrolls near the image, improving initial page load performance.Question 6: What image format is best for logos with transparency?
Show answer
SVG for simple logos (infinitely scalable), or PNG for complex logos with many colors. WebP is also excellent for modern browsers with PNG fallback.14. Common Mistakes
Missing Alt Attribute
<img src="photo.jpg">
<img src="photo.jpg" alt="Sunset over mountains">
Using Images for Text
<img src="heading-text.png" alt="Welcome to Our Site">
<h1>Welcome to Our Site</h1>
Forgetting Width/Height
<img src="photo.jpg" alt="Photo">
<img src="photo.jpg" alt="Photo" width="800" height="600">
Not Optimizing File Sizes
<img src="photo-original-4000x3000.jpg" alt="Thumbnail" width="200">
<img src="photo-thumb-200x150.jpg" alt="Thumbnail" width="200" height="150">
15. Key Takeaways
- Always include
altattribute - Required for accessibility (usealt=""for decorative) - Specify
widthandheight- Prevents layout shift (CLS) - Choose correct format - JPEG (photos), PNG (graphics), WebP (modern), SVG (vectors)
- Use
srcsetandsizes- Serve appropriate image sizes for different screens - Use
<picture>- For art direction and format fallbacks - Lazy load below-fold images -
loading="lazy"improves performance - Optimize file sizes - Compress images, use appropriate dimensions
- Use
<figure>and<figcaption>- For images with captions - Provide video/audio fallbacks - Multiple source formats for compatibility
- Write descriptive alt text - Describe content and purpose, not just appearance
16. Further Resources
Official Documentation:
Image Optimization:
Accessibility:
Next Steps
Excellent work! You now know how to add and optimize images and media for modern web development.
In Lesson 2.5: Tables & Data, you'll learn how to structure and present tabular data with HTML tables, including accessibility features and responsive techniques.