Search code examples
htmlcssimageresponsivesizing

Fit image on screen CSS


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>


Solution

  • 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?