Skip to content

CSS Tutorial CSS Responsive Design

Responsive Images in CSS

Lesson 114 of 182 2 min read By Deepak Paswan Updated Oct 4, 2026

The first rule

style.css
CSS
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.

index.html
HTML
<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>
style.css
CSS
.card img {
  width: 100%;
  aspect-ratio: 16 / 9;
  object-fit: cover;
}
  • aspect-ratio: 16 / 9 fixes the shape. It also reserves space before the image loads, which stops the page from jumping.
  • object-fit: cover fills the shape and crops the extra. contain fits the whole image inside and leaves gaps.
  • object-position chooses which part is kept, for example object-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:

index.html
HTML
<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.

warning
Lost alt text
The alt attribute is not optional for meaningful images. Describe what is shown, not “image of”. Decorative pictures take alt="".