Home > Software design >  How to make an Height and Width Responsive Image with Kept Ratio in html and css?
How to make an Height and Width Responsive Image with Kept Ratio in html and css?

Time:08-18

There exist many similar questions, but none has yet solved my requirements:

  • Aspect ratio should be kept, AND
  • Height responsive, AND
  • Width responsive, AND
  • Full image should always be seen within the browser window (i.e. the responsiveness should be with regards to the tightest dimension).

I have achieved these requirements, but not all of them in the same time. For example:

If I let the code below as it is with height="90%" width="auto" then it is height responsive but not width responsive.

If I change to height="auto" width="90%" then it is width responsive but not height responsive.

If I change to height="90%" width="90%" then it is both height and width responsive, but the ratio is not kept.

To test, please "Run code snippet" and check with "Full page" the situation by changing both height and width of the browser window.

.test {
  height: 90vh;
  width: 90%;
  background-color: #222;
  color: #eee;
  padding: 2rem;
}

.test img {
  align-items: center;
}
<div >
  <img height="90%" width="auto" src="https://images.unsplash.com/photo-1418065460487-3e41a6c84dc5?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw=&ixlib=rb-1.2.1&auto=format&fit=crop&w=1600&q=80">
</div>

I have tested in many different ways (e.g. with max-width, etc.) but not succeeded so far. Any idea how to change the above code so that all requirements are fulfilled simultaneously?

CodePudding user response:

You can use max-width and max-height together on the image then it will keep your aspect ratio and always fit on the screen with the complete image showing

body {
  margin: 0;
}

.test {
  background-color: #222;
  color: #eee;
  padding: 2rem;
  height: 90vh;
  width: 90%;
  box-sizing: border-box;
}

.test img {
  margin: auto;
  display: block;
  max-width: 100%;
  max-height: 100%;
}
<div >
  <img src="https://images.unsplash.com/photo-1418065460487-3e41a6c84dc5?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw=&ixlib=rb-1.2.1&auto=format&fit=crop&w=1600&q=80">
</div>

CodePudding user response:

try this in your css:

.test img {
   object-fit: cover;
   width: 100%;
   height: auto;
}
  • Related