Fit image on screen CSS

187 Views Asked by At

I want all of this sample HTML structure to fit 1 screen without scrolling, the image has to resize appropriately. But there is still scrolling.

<div style="position: fixed; top:0;left:0;width:100vw;height:100vh;background:red;z-index:100000;display:flex;flex-direction:column">
    <div style="background:green">aaa</div>
    <div style="flex-grow:1">
        <img src="https://placehold.co/3200x3200" style="width: 100%; height: 100%; object-fit: contain;">
    </div>
    <div style="background:blue">bbb</div>
</div>

2

There are 2 best solutions below

3
Paradonix On BEST ANSWER

Your div wrapped around your image doesn't have a set height and matches the height of your image. This results in the image being bigger than the screen. Try giving the div a height of 100%. This will match its parents height, which is the screen height.

Here's an example:

<div style="position: fixed; top:0;left:0;width:100vw;height:100vh;background:red;z-index:100000;display:flex;flex-direction:column">
    <div style="background:green">aaa</div>
    <div style="display:flex;flex-grow:1;height:100%;overflow:auto;">
        <img src="https://placehold.co/3200x3200" style="width: 100%; height: 100%; object-fit: contain;">
    </div>
    <div style="background:blue">bbb</div>
</div>

Is this what you were looking for?

0
Pete On

You could use absolute positioning on your image to make sure it fills the parent div. Also, I would change your object fit to cover rather than contain, otherwise it won't fill the full area unless the area and the image have the same aspect ratio (if you're not bothered about that, then you can leave it as contain).

<div style="position: fixed; top:0;left:0;width:100vw;height:100vh;background:red;z-index:100000;display:flex;flex-direction:column">
    <div style="background:green">aaa</div>
    <div style="flex-grow:1; position:relative;">
        <img src="https://placehold.co/3200x3200" style="object-fit: cover; position:absolute; top: 0; left:0; width: 100%; height: 100%;">
    </div>
    <div style="background:blue">bbb</div>
</div>