0

I have spent 2 hours trying to solve this simple problem. I need a tall img to fit inside a div. This div must resize with the browser height. But it always overflows, not matter what I try. There is some text below the img that must appear.

<html style="height: 100%">
  <body style="height: 100%; overflow: hidden; margin: 0">
    <div id="div-1" style="display: flex; flex-direction: column; height:100%">
      <div id="div-2" style="min-height:0px;" >
          <div id="div-3" style="min-height:0px;" >
              <img src="https://images.unsplash.com/photo-1465680949814-1ed23ecb963f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80"
                   style="max-width:100%; max-height:100%; object-fit: contain"/>
          </div>
      </div>
      <div style="height:30px">This text should be displayed below the image</div>
    </div>
  </body>
</html>

https://codepen.io/orobert91/pen/MWwZLGV

When inspecting elements, you can see that the body, div-1 and div-2 have the right height, but div-3 overflows.

Solutions over the Internet suggest to put max-width, max-height, object-fit to the img, also some suggest to wrap the img inside a block div, which I did, but it does not work in my case. I don't know what else to do.

olivierr91
  • 1,243
  • 3
  • 13
  • 29

2 Answers2

0

Whenever you set an img, you can modify it to the div it's inside

if you set in your css

img {
  height: 100%;
  width: 100%;
}
#div-2 {
  height: 200px;
  width: 200px;
}

the img will be the full size of the div and you can then just resize and move around the div and the img will stay the full size of the div

ShrewdStyle
  • 500
  • 2
  • 5
  • 14
0

Not the best, but it works

<html style="height: 100%">
  <body style="height: 100%; overflow: hidden">
    <div id="div-1" style="display: flex; flex-direction: column; align-content: stretch; height:100%">
      <div id="div-2" style="flex: 1 1 auto;  overflow: hidden">
          <img src="https://images.unsplash.com/photo-1465680949814-1ed23ecb963f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80"
               style="object-fit: contain"/>
      </div>
      <div style="flex: 0 1 auto; min-height: 30px">This text should be displayed.</div>
    </div>
  </body>
</html>
focus.style
  • 6,612
  • 4
  • 26
  • 38