Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

object-fit on responsive image

Tags:

css

I have images that are 1000px wide by 250px high. I've made the images responsive/flexible by using

img { 
max-width:1000px; 
height:auto; 
}

All the images should be in this ratio of 1 to 1/4.

However the client will from now on be using a CMS to replace and update images. I have no control over the dimensions of these new images. The CMS isn't capable of scaling and cropping the new images to the required format. I have been told to use object:fit. Such as:

img { 
width:1000px;
height:250px;
object-fit:cover;
}

However these means the images are not responsive/flexible. Is there a way to keep the images responsive and for the ratio to stay the same?

I've tried the following but they don't work:

img {
max-width: 100%;
max-height: 252px;
object-fit: cover;
}

and

img {
max-width: 100%;
height: auto;
object-fit: cover;
}

I could use background images and the padding-bottom:25% trick, but I'd rather use images and alt tags.

like image 362
user2991837 Avatar asked Dec 23 '25 02:12

user2991837


1 Answers

Update 2022

Now you can rely on aspect-ratio

img.responsive {
  width: 100%;
  aspect-ratio:4;
  object-fit: cover;
}
<img src="https://picsum.photos/id/1000/1000/1000" alt="image" class="responsive">
<img src="https://picsum.photos/id/1074/1000/1000" alt="image" class="responsive">

Old answer

You can combine the use of img and the padding trick. You only need to add an extra inline style for the background-image that you make the same as the src:

img {
  width: 100%;
  height: 0;
  padding-top: 25%;
  background-size: cover;
  background-position: center;
}
<img src="https://picsum.photos/id/1000/1000/1000" style="background-image:url(https://picsum.photos/id/1000/1000/1000g)" alt="image">

With a small JS code you can have this automatically:

$('.responsive').each(function() {
  $(this).css('background-image','url('+$(this).attr('src')+')');
})
img.responsive {
  width:100%;
  height:0;
  padding-top:25%;
  background-size:cover;
  background-position:center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://picsum.photos/id/1000/1000/1000"  alt="image" class="responsive">
<img src="https://picsum.photos/id/1074/1000/1000"  alt="image" class="responsive">
like image 174
Temani Afif Avatar answered Dec 24 '25 16:12

Temani Afif



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!