1

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.

Jonathan002
  • 9,639
  • 8
  • 37
  • 58

2 Answers2

0

Instead of using the <img> tag you can just give the <div> a background image with background-size: cover property. The background image will maintain the aspect ratio while covering the entire div container at all times.

<div></div>

div {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%, 0);
  height: 80vh;
  width: 80%;
  background: red url("http://i.imgur.com/kOY2G57.jpg") center center;
  background-size: cover;
  position: relative;
  overflow: hidden;
}
Hemant Parashar
  • 3,684
  • 2
  • 16
  • 23
  • Thanks for the answer, although I hope to stay away from background images as I have to program my img tags in my project to be a background img. I'm trying to get away with a non programing solution if possible : ) – Jonathan002 Mar 14 '17 at 10:37
-1

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="">
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313