Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Responsive images with fixed height CSS

I want to fit an image in a div which has a fixed height and the image should expand to 100% without messing with the aspect ratio and also want the image to be responsive. I tried this,

img{
    height:500px;
    width:100%;
  }

This messes the aspect ratio. How can I fix that?

like image 574
Melissa Stewart Avatar asked Aug 04 '26 15:08

Melissa Stewart


1 Answers

You can do it with CSS object-fit:

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

Or contain depends on your needs.

like image 158
Stickers Avatar answered Aug 07 '26 05:08

Stickers