Responsive Images
Scale images to fit their container.
Syntax
img { max-width: 100%; height: auto; }To keep images from overflowing their container, set max-width: 100% and height: auto. The image then scales down on small screens while keeping its aspect ratio.
The object-fit property controls how an image fills a fixed-size box: cover crops, contain fits the whole image.
Example
Loading editorβ¦
Press Run to see the result.
When to use it
- A developer sets max-width: 100% on all images so they never overflow their parent containers on narrow screens.
- A designer uses object-fit: cover on a fixed-height image container so the photo always fills the box and stays cropped rather than squished.
- A developer uses the srcset attribute with CSS max-width so browsers load appropriately sized images based on device resolution.
More examples
Fluid image with max-width
The three-line global rule that makes every image fluid β it scales down on narrow screens but never exceeds its natural size.
img {
max-width: 100%;
height: auto;
display: block;
}object-fit cover for aspect ratio
Crops an image to fill a fixed-height container at any width, positioning the subject at the center-top with object-position.
.card-image {
width: 100%;
height: 200px;
object-fit: cover;
object-position: center top;
border-radius: 8px 8px 0 0;
}Responsive srcset in HTML
Uses srcset and sizes so browsers download only the appropriate image resolution for the current device and viewport width.
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
sizes="(max-width: 600px) 100vw, 50vw"
alt="Responsive photo"
style="max-width: 100%; height: auto;"
>
Discussion