The first rule
img {
max-width: 100%;
height: auto;
}
An image can never be wider than its container, and its height follows to keep its proportions. If you only add width: 100% an image smaller than the container is stretched and goes blurry. max-width stops at the image’s natural size.
Fixed-shape images with object-fit
A grid of photos looks tidy when all of them have the same shape. object-fit crops an image to fill a box without squashing it.
<style>
.photo {
width: 100%; max-width: 280px; aspect-ratio: 16 / 9;
background: linear-gradient(135deg, #1a5276, #d94a00);
border-radius: 8px; display: block;
}
</style>
<div class="photo"></div>
.card img {
width: 100%;
aspect-ratio: 16 / 9;
object-fit: cover;
}
aspect-ratio: 16 / 9fixes the shape. It also reserves space before the image loads, which stops the page from jumping.object-fit: coverfills the shape and crops the extra.containfits the whole image inside and leaves gaps.object-positionchooses which part is kept, for exampleobject-position: top.
Responsive background images
For backgrounds, background-size: cover does the same job.
Serving smaller files to small screens
CSS shapes images but does not shrink their file size. A 3000px photo on a phone is still a big download. The HTML srcset attribute lets the browser pick the right file:
<img src="book-800.jpg"
srcset="book-400.jpg 400w, book-800.jpg 800w, book-1600.jpg 1600w"
sizes="(min-width: 768px) 50vw, 100vw"
alt="Open book on a wooden table" width="800" height="533">
Also set width and height attributes: browsers use them to work out the aspect ratio before the file arrives.
Lost alt text
alt attribute is not optional for meaningful images. Describe what is shown, not “image of”. Decorative pictures take alt="".