Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS - How to stretch images vertically to fill when parent div doesn't have fixed height. (Without flex)

Tags:

html

css

I have 2 images that have different dimensions. I want them to align horizontally and to fill the same height.

HTML

<div class="background">
  <div class="wrapper">
    <div class="content">
      <img src="./nat-8.jpg" alt="" />
      <img src="./nat-9.jpg" alt="" />
    </div>
  </div>
</div>

CSS

.background {
  height: 100vh;
  width: 100%;
  background-color: grey;
  position: relative;
}

.content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  background-color: white;
}

img {
  display: inline-block;
  width: 35%;
}

The result I get: enter image description here

As you can see the first picture has white space left on the top. How do I make it that each picture covers the whole height of parent without setting fixed height on parent?

NOTE: I know that it can be done with flex by setting 'display:flex' on content div. But how do I do it without flexbox? I tried 'display:table-cell' on images, in one solution I found it was used to make divs fill the entire eight of their parent, but apparently it does not work on 'img' element.

like image 335
John Doe Avatar asked Oct 11 '25 08:10

John Doe


1 Answers

You need to set the height of the parent container, then you can set the height of the image to 100% to fill the space.

You can then use object-fit:cover to keep the image ratio rather than stretching. You can also use object-position:center to keep the positioning centered also.

Not all browsers are compatible with object-fit, so I would suggest swapping out the images for divs with a background-image set.

.background {
  height: 100vh;
  width: 100%;
  background-color: grey;
  position: relative;
}

.wrapper{
  height:100%;
}

.content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  background-color: white;
  height:100%;
  max-height:150px;
}

img {
  display: inline-block;
  width: 35%;
  height:100%;
  object-fit:cover;
  object-position:center;
}
<div class="background">
  <div class="wrapper">
    <div class="content">
      <img src="https://www.indiewire.com/wp-content/uploads/2019/06/574055-frank_ockenfels-amc.jpg" alt="" />
      <img src="https://www.indiewire.com/wp-content/uploads/2019/06/574055-frank_ockenfels-amc.jpg" alt="" />
    </div>
  </div>
</div>
like image 115
Tyler Watts Avatar answered Oct 16 '25 09:10

Tyler Watts