CSS RWD Images
In this page:
The Core Fluid Image Rule
Setting max-width: 100% and height: auto on an image lets it shrink to fit any container narrower than its natural size while preserving its aspect ratio, without ever growing past its actual pixel dimensions and becoming blurry.
Example: The Core Fluid Image Rule
<style>
img {
max-width: 100%;
height: auto;
}
</style>
<img src="https://placehold.co/1200x800" alt="Shrinks to fit, keeps its aspect ratio">
Why height: auto Matters
Setting only max-width: 100% without height: auto can leave the height fixed at the image's natural pixel height even as the width shrinks, distorting the image -- height: auto tells the browser to recalculate height proportionally as width changes.
Example: Why height: auto Matters
<style>
.distorted {
max-width: 100%;
}
.correct {
max-width: 100%;
height: auto;
}
</style>
<img class="distorted" src="https://placehold.co/800x400" alt="Height stays fixed, can distort">
<img class="correct" src="https://placehold.co/800x400" alt="Height recalculates proportionally">
Serving Different Image Sizes
A single large image scaled down with CSS still downloads its full file size even on a small phone screen, wasting bandwidth -- the HTML srcset and sizes attributes (and the <picture> element for art-direction cases) let the browser choose an appropriately-sized file per device.
Example: Serving Different Image Sizes
<img srcset="small.jpg 480w, large.jpg 1200w"
sizes="(max-width: 600px) 480px, 1200px"
src="large.jpg" alt="Browser picks the right file size per device">
Background Images vs Inline Images
background-image in CSS does not respond to max-width/height: auto the same way <img> does -- responsive background images instead rely on background-size: cover or contain, combined with media queries to swap the image file itself if needed.
Example: Background Images vs Inline Images
<style>
.hero {
background-image: url('https://placehold.co/1200x400');
background-size: cover;
height: 200px;
}
</style>
<div class="hero">background-size handles responsiveness here, not max-width</div>
object-fit for Cropped Responsive Images
When an image must fill a fixed-aspect-ratio box exactly (like a square avatar or card thumbnail) without distortion, object-fit: cover crops the image to fill the box while object-fit: contain letterboxes it instead -- both work with any container size.
Example: object-fit for Cropped Responsive Images
<style>
img {
width: 150px;
height: 150px;
object-fit: cover;
}
</style>
<img src="https://placehold.co/400x200" alt="Cropped to fill the square without distortion">
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: