Responsive Images & Typography
Images are the biggest performance bottleneck on most websites. Responsive images adapt their size, resolution, and format to the device — saving bandwidth on mobile and looking sharp on retina displays.
Responsive Image Techniques
- max-width: 100% — The minimum: prevents images from overflowing containers. height: auto maintains ratio
- object-fit: cover — Fills the container while maintaining aspect ratio (crops if needed). Like background-size: cover
- object-fit: contain — Fits entire image inside container (may have empty space). No cropping
- aspect-ratio: 16/9 — Sets a consistent aspect ratio. Reserves space before image loads (prevents layout shift)
- width/height attributes — Always set on <img> tags. Browser reserves space, reducing Cumulative Layout Shift (CLS)
- loading='lazy' — Native lazy loading. Images load only when they're close to the viewport. Free performance win
- srcset — Serve different image sizes: srcset='img-320.jpg 320w, img-640.jpg 640w'. Browser picks the best one
Responsive Images Code
/* Basic responsive image */
img {
max-width: 100%;
height: auto;
display: block;
}
/* Card with consistent image height */
.card-image {
width: 100%;
height: 200px;
object-fit: cover; /* Fill and crop */
border-radius: 12px 12px 0 0;
}
/* Maintain aspect ratio */
.hero-image {
width: 100%;
aspect-ratio: 16 / 9;
object-fit: cover;
}
/* Circle avatar */
.avatar {
width: 64px;
height: 64px;
border-radius: 50%;
object-fit: cover;
}
/* Background image responsive */
.bg-section {
background: url('hero.jpg') center/cover no-repeat;
min-height: 60vh;
}Tip
Always add loading='lazy' to below-the-fold images. It's a one-attribute addition that defers image loading until the user scrolls near them, reducing initial page load time significantly. Hero images and above-the-fold images should NOT be lazy loaded — they should load immediately.
Mobile-first: start with mobile styles, enhance with min-width media queries
Common Mistake
Using max-width: 100% alone as your 'responsive image solution.' While this prevents overflow, it doesn't set height: auto, so images may distort. Always use both: max-width: 100%; height: auto. For card images where you need a fixed height, use object-fit: cover.
Practice Task
Audit your image CSS: (1) Add max-width: 100%; height: auto; display: block to all images as a global reset, (2) Convert card images to use aspect-ratio: 16/9 + object-fit: cover instead of fixed height, (3) Add loading='lazy' to all images except the first visible one on the page.
Quick Quiz
Key Takeaways
- Images are the biggest performance bottleneck on most websites.
- max-width: 100% — The minimum: prevents images from overflowing containers. height: auto maintains ratio
- object-fit: cover — Fills the container while maintaining aspect ratio (crops if needed). Like background-size: cover
- object-fit: contain — Fits entire image inside container (may have empty space). No cropping