← Back to Course

Module 09

Images & Media

Optimizing images, aspect ratios, and responsive media. Master the visual assets that make or break your site's performance and aesthetics.

From GIF and JPEG to WebP and AVIF. Image formats keep evolving for better compression. Tools like Squoosh, ImageOptim, and CDNs automate optimization.

Lazy loading became standard. WebP reached 95%+ browser support. AVIF is the new frontier. Performance budgets now include image-specific targets.

Right format, right size, right quality. Images should enhance content, not slow it down. Every byte matters on mobile. Optimize ruthlessly.

Part A

Core Concepts

01

Image Formats

Each format has strengths. Choose based on content, not habit.

Best for: photographs, complex images

Lossy compression | No transparency

JPEG for Photos

JPEG excels at photographs with smooth gradients and millions of colors. Quality 80-85% is usually indistinguishable from 100% but significantly smaller.

Checkerboard = transparency

PNG for Transparency

PNG supports alpha transparency and lossless compression. Use PNG-8 for simple graphics with few colors, PNG-24 for transparency needs.

WebP

25-35% smaller than JPEG

Lossy + Lossless + Transparency + Animation

WebP - Modern Choice

WebP does it all - photos, transparency, and animation. Supported by 95%+ of browsers. Should be your default format for most images.

Scales infinitely, tiny file size

SVG for Vectors

SVG is code, not pixels. Perfect for icons, logos, and illustrations. Scales to any size without quality loss. Can be styled with CSS and animated.

AVIF

50% smaller than JPEG

Slower to encode | Growing browser support

AVIF - The Future

AVIF offers best-in-class compression. Use with fallbacks via picture element. Worth implementing for high-traffic sites.

02

Optimization

Every image should be optimized. No exceptions.

60-70%

Thumbnails

75-85%

Standard

90-95%

Hero images

Quality Settings

Most images can use 75-85% quality without visible degradation. Reserve 90%+ for hero images. Thumbnails can go as low as 60%.

Don't: Upload 4000x3000px photo

Don't: Let CSS scale it to 400x300

Do: Resize to actual display size

Do: Provide 2x for retina displays

Right-Sizing Images

Never serve images larger than their display size. A 4000px image scaled to 400px wastes 99% of pixels. Resize before uploading.

Squoosh - Browser-based, visual comparison

ImageOptim - Mac app, batch processing

Sharp - Node.js, build integration

Cloudinary/imgix - CDN with auto-optimization

Optimization Tools

Use Squoosh for one-off optimization with visual feedback. ImageOptim for batch processing. Sharp for build pipelines. CDNs for dynamic optimization.

EXIF data in photos:

Camera model, GPS coordinates, date/time, thumbnail...

This adds 20-100KB+ per image

Strip it. Your users don't need it.

Strip Metadata

Photos from cameras contain metadata that adds significant file size. Most optimization tools strip this automatically. Verify it's being removed.

03

Aspect Ratios

Consistent ratios create visual harmony and prevent layout shift.

1:1 Square

4:3 Classic

16:9 Wide

21:9 Ultra

Standard Aspect Ratios

1:1 for avatars and thumbnails. 4:3 for traditional photos. 16:9 for video and hero images. Choose ratios intentionally and use them consistently.

.thumbnail {

aspect-ratio: 16 / 9;

width: 100%;

object-fit: cover;

}

aspect-ratio Property

The aspect-ratio CSS property reserves space before images load. Combined with object-fit: cover, images fill the space without distortion.

cover

contain

fill

Fitting Images

object-fit: cover crops to fill (most common). contain fits entire image with letterboxing. fill stretches to fill (usually bad).

Without dimensions:

Image loads → content jumps down

User clicks wrong thing → frustrated

Solution:

Always set width/height or aspect-ratio

Cumulative Layout Shift

Layout shift happens when images load without reserved space, pushing content around. Core Web Vital metric. Always reserve space for images.

04

Responsive Images

Serve the right image for each device and context.

<img

src="photo-800.jpg"

srcset="photo-400.jpg 400w,

photo-800.jpg 800w,

photo-1200.jpg 1200w"

sizes="(max-width: 600px) 100vw, 50vw"

alt="...">

Resolution Switching

srcset lists available sizes. sizes tells browser how big the image will display. Browser picks optimal file based on screen and network.

<picture>

<source media="(min-width: 800px)"

srcset="hero-wide.webp"

type="image/webp">

<source media="(max-width: 799px)"

srcset="hero-square.webp"

type="image/webp">

<img src="hero-wide.jpg" alt="">

</picture>

Art Direction

Use picture for art direction - different crops for different screens. Wide landscape on desktop, square crop on mobile.

<picture>

<source srcset="photo.avif" type="image/avif">

<source srcset="photo.webp" type="image/webp">

<img src="photo.jpg" alt="">

</picture>

Modern Formats with Fallback

Browsers pick the first format they support. Serve AVIF, fall back to WebP, final fallback to JPEG. Best of all worlds.

<img

src="photo.jpg"

loading="lazy"

width="800"

height="600"

alt="...">

Native Lazy Loading

loading='lazy' defers loading until image is near viewport. Native, no JavaScript required. Don't use on above-the-fold images.

05

Video & Media

Video requires special handling for performance and accessibility.

.video-container {

aspect-ratio: 16 / 9;

width: 100%;

}

.video-container iframe {

width: 100%;

height: 100%;

}

Responsive Video Embed

Wrap video embeds in a container with aspect-ratio. The iframe fills its container. No more padding-bottom hacks.

<video

controls

preload="metadata"

poster="thumbnail.jpg">

<source src="video.webm" type="video/webm">

<source src="video.mp4" type="video/mp4">

</video>

HTML5 Video

Self-hosted video with multiple sources. WebM for modern browsers, MP4 as fallback. poster shows before playback. preload='metadata' for performance.

<video

autoplay

muted

loop

playsinline

poster="fallback.jpg">

</video>

muted required for autoplay

Background Video

Autoplay requires muted (browser policy). loop for continuous play. playsinline prevents fullscreen on iOS. Always provide poster fallback.

Compress aggressively - Video tolerates more compression than photos

Use YouTube/Vimeo - They handle transcoding, CDN, adaptive bitrate

Lazy load embeds - Show thumbnail, load player on click

Consider GIFs → Video - MP4 is often smaller than GIF

Video Performance Tips

Video is expensive. Use third-party hosts when possible. If self-hosting, compress aggressively and lazy-load when possible.

Part C

Science & Psychology

10

The Science of Visual Perception

How humans perceive images - and what it means for optimization.

Can you tell which is 100% vs 80% quality?

Visual Quality Perception

Human vision has limits. We can't perceive every byte of quality. Research shows most people can't distinguish 85% JPEG from 100% in normal viewing conditions.

Thumbnail

60% quality is fine

Lightbox

Higher quality matters

Viewing Context Matters

Small images viewed briefly need less quality than large images examined closely. Adjust compression based on how images will be viewed.

Progressive JPEG:

Blurry → sharp feels fast

Baseline JPEG:

Top-to-bottom feels slow

Perceived Performance

Progressive JPEGs render a blurry preview immediately, then sharpen. Users perceive this as faster than baseline JPEGs that load line-by-line from top.

3G (1.5 Mbps): 1MB image = 5.3 seconds

4G (12 Mbps): 1MB image = 0.67 seconds

5G/WiFi: 1MB image = instant

Many users still have 3G-like speeds. Design for them.

Real-World Networks

Your fast connection isn't everyone's reality. Many users have slow or metered connections. Every KB you save helps real people.

Part D

Real-World Examples

11

Image Strategies in Practice

How major sites handle images at scale.

Netflix
Principles Identified:
Dynamic optimization Different artwork for different contexts - TV gets different image than mobile
A/B tested thumbnails They test which image variants drive more clicks
WebP everywhere Moved to WebP years ago, saving huge bandwidth
Pinterest
Principles Identified:
Aggressive lazy loading Only loads images about to enter viewport
Dominant color placeholder Shows image's dominant color while loading
Progressive enhancement Low-quality preview, then full image
Medium
Principles Identified:
Blur-up technique Tiny placeholder image scales up blurry, then sharp image loads
Automatic optimization Writers upload any image, system optimizes
Consistent aspect ratios Images fit into predictable spaces

Part G

CSS Implementation

14

CSS Implementation

Image patterns you can use today.

img {
  max-width: 100%;
  height: auto;
  display: block;
}

/* For specific ratios */
.thumbnail {
  aspect-ratio: 1 / 1;
  object-fit: cover;
}
Responsive Image Base via CSS
  • max-width: 100% - Never exceed container
  • height: auto - Maintain aspect ratio
  • display: block - Remove inline spacing
.image-container {
  background: #f0f0f0; /* Loading placeholder */
  aspect-ratio: 16 / 9;
}

.image-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
Image with Fallback Color via CSS
  • background - Shows while image loads
  • aspect-ratio - Reserves space, prevents CLS
  • object-fit: cover - Fills space without distortion
.video-facade {
  aspect-ratio: 16 / 9;
  background: url('thumbnail.jpg') center/cover;
  cursor: pointer;
  position: relative;
}

.video-facade::after {
  content: '';
  /* Play button overlay */
  position: absolute;
  /* ... play button styles ... */
}
Lazy Loading Facade via CSS
  • Static thumbnail - Shows until clicked
  • Play button overlay - Indicates interactivity
  • JS loads player - Iframe injected on click

  
  
  Hero image
Art Direction with Picture via CSS
  • source elements - Declare alternatives
  • media queries - Target viewport sizes
  • type attribute - Specify format for fallback chain

Part H

Self-Assessment

15

Self-Assessment

Test your image optimization knowledge.

Q1

When should you use WebP instead of JPEG?

Click to reveal
Q2

What does loading='lazy' do?

Click to reveal
Q3

Why is aspect-ratio important for images?

Click to reveal
Q4

What's the difference between srcset and picture?

Click to reveal
Q5

What JPEG quality should you typically use?

Click to reveal

Key Takeaways

WebP by default

WebP

25-35% smaller

Use WebP as your default format. It handles photos and transparency. Fall back to JPEG/PNG for older browsers. Use AVIF for maximum compression.

Right-size everything

Display size: 400px

Serve: 800px (2x retina)

Not 4000px

Never serve images larger than 2x their display size. Use srcset to let browsers choose the right size for their screen.

Lazy load below fold

loading="lazy"

Add loading='lazy' to images below the fold. Don't use it on hero images or anything visible on initial load.

Reserve space always
Space reserved

Use aspect-ratio or explicit width/height to prevent layout shift. Content that jumps around as images load frustrates users.