CGPA Calculator Hash Generator Bcrypt Hasher Tree Visualizer Barcode Generator Engineering Blog Editorial Standards All Tools Games HTML5 JavaScript PHP MySQL

CSS Responsive Images

For your website to be truly mobile-friendly, your images must be fluid and adapt to different screen widths. Without proper styling, large images will break your layout on small screens.


The max-width Property

The simplest way to make an image responsive is by setting max-width: 100% and height: auto. This ensures the image shrinks if its container is smaller than the image's original width, but never grows larger than its native size.

Nature
img {
    max-width: 100%;
    height: auto;
}

Fluid Background Images

When using an image as a background on a <div>, the background-size: cover property is essential. It tells the browser to scale the image proportionally so that it covers the entire background area.

div {
    width: 100%;
    height: 400px;
    background-image: url('img.jpg');
    background-size: cover;
    background-position: center;
}

Adaptive Images with <picture>

Sometimes you need to show completely different images for mobile and desktop (e.g., a landscape photo for desktop and a portrait-oriented crop for mobile). The <picture> element handles this perfectly.

<picture>
  <source media="(min-width: 650px)" srcset="desktop.jpg">
  <source media="(min-width: 465px)" srcset="tablet.jpg">
  <img src="mobile.jpg" alt="Responsive Image" style="width:auto;">
</picture>

Tip: Always include the alt attribute for images. This makes your site accessible to blind users and helps search engines understand your content.