How to resize an image to fit in the browser window?

Here is a simple CSS only solution (JSFiddle), works everywhere, mobile and IE included:

CSS 2.0:

html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}

img {
    padding: 0;
    display: block;
    margin: 0 auto;
    max-height: 100%;
    max-width: 100%;
}

HTML:

<body>
  <img src="images/your-image.png" />
</body>

Update 2018-04-11

Here's a Javascript-less, CSS-only solution. The image will dynamically be centered and resized to fit the window.

<html>
<head>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        .imgbox {
            display: grid;
            height: 100%;
        }
        .center-fit {
            max-width: 100%;
            max-height: 100vh;
            margin: auto;
        }
    </style>
</head>
<body>
<div class="imgbox">
    <img class="center-fit" src='pic.png'>
</div>
</body>
</html>

The [other, old] solution, using JQuery, sets the height of the image container (body in the example below) so that the max-height property on the image works as expected. The image will also automatically resize when the client window is resized.

<!DOCTYPE html>
<html>
<head>
    <style>
        * {
            padding: 0;
            margin: 0;
        }
        .fit { /* set relative picture size */
            max-width: 100%;
            max-height: 100%;
        }
        .center {
            display: block;
            margin: auto;
        }
    </style>
</head>
<body>

<img class="center fit" src="pic.jpg" >

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" language="JavaScript">
    function set_body_height() { // set body height = window height
        $('body').height($(window).height());
    }
    $(document).ready(function() {
        $(window).bind('resize', set_body_height);
        set_body_height();
    });
</script>

</body>
</html>

Note: User gutierrezalex packaged a very similar solution as a JQuery plugin on this page.


CSS3 introduces new units that are measured relative to the viewport, which is the window in this case. These are vh and vw, which measure viewport height and width, respectively. Here is a simple CSS only solution:

img {
    max-width: 100%;
    max-height: 100vh;
    height: auto;
}

The one caveat to this is that it only works if there are no other elements contributing height on the page.

Tags:

Html

Css