Search code examples
htmlcssfluid-layoutfluid-images

fluid images inside a fluid container that changes aspect ratio


Hi I have a fluid container that is based on screen height and width in my website. I would like to have an image fill the container at all times as it expands in any direction based on screen size. The images used will vary in size and aspect ratio.

I have made an attempt with html and css below:

div {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%, 0);
  height: 80vh;
  width: 80%;
  background-color: red;
  position: relative;
  overflow: hidden;
}

img {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  min-height: 100%;
  min-width: 100%;
  width: auto;
  height: auto;
  /*  max-width: 100%; // If used Image needs to be tall enough to fill div */
  /*  max-height: 100%; // If used Image needs to be wide enough to fill div */
}
<div>
  <img src="http://i.imgur.com/kOY2G57.jpg">
</div>

Without max-height and max-width, this works well if the img is smaller than the container but does not work if the images come out larger as they come out in their natural size and get cropped.

jsfiddle example

Is it possible to accomplish this task with just pure css?

Update I also would like to avoid using background images as a solution and see if this is possible with just the img tag in place at the dom so as to avoid programing the img tags if possible.


Solution

  • Use object-fit for images to achieve the same result akin to background-size cover, contain:

    .imgFit {
        object-fit: cover;   /* cover, contain */
        display: block;
        width: 100%;
        height: 100%;
    }
    

    Use like:

    <img class="imgFit" src="" alt="">