0

I have this html

.picture-image {
    height: 100vh;
    overflow: hidden;
    position: relative;
}
.picture-image > img {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  object-fit: contain;

}
<div class="picture">
  <div class="picture-image">
    <img alt="" src="">
  </div>
</div>

This displays a div with height and width matching the screen, and the image is centered in it, adapting to the div size. It is pretty nice on desktop screens but not in mobile where we usually have a portrait orientation, and this solution causes to show a lot of white space above and below the image.

What can I do to reduce the height (not the width) of the div to match the image height?

If you think there's a better way to display a single image on both desktop and mobile I am open to suggestions.

MaxiGui
  • 6,190
  • 4
  • 16
  • 33
user3174311
  • 1,714
  • 5
  • 28
  • 66
  • 1
    _"What can I do to reduce the height (not the width) of the div to match the image height?"_ - don't specify a height, and don't position the image absolute? Give it width:100% and height: auto, and let it determine the height of the parent div then ... – CBroe May 31 '22 at 07:49

1 Answers1

1

Add to your picture-image:

display: flex;
justify-content: center;
align-items: center;

And on your image:

max-width: 100%;
max-height: 100%;

DEMO

.picture-image {
  height: 100vh;
  /*overflow: hidden;
  position: relative;*/
  display: flex;
  justify-content: center;
  align-items: center;
}
.picture-image > img {
  /*position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;*/
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;

}
<div class="picture">
  <div class="picture-image">
    <img alt="" src="https://dummyimage.com/1600x600/000/fff">
  </div>
</div>
MaxiGui
  • 6,190
  • 4
  • 16
  • 33