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.
max-width PropertyThe 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.
img {
max-width: 100%;
height: auto;
}
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;
}
<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>
alt attribute for images. This makes your site accessible to blind users and helps search engines understand your content.