sebnukem sebnukem - 4 years ago 192
HTML Question

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

This seems trivial but after all the research and coding I can't get it to work. Conditions are:


  1. The browser window size is unknown. So please don't propose a solution involving absolute pixel sizes.

  2. I do not wish scrollbars to appear (and they shouldn't if the image fits.)

  3. The image may or may not already fit the browser window. It is always centered.

  4. The image proportions must be conserved.

  5. The image must be displayed in its entirety in the window (no cropping.)



Basically what I want is this:

.fit {
max-width: 99%;
max-height: 99%;
}
<img class="fit" src="pic.png">


The problem with the code above is that it doesn't work: the pic takes all the vertical space it needs by adding a vertical scroll bar.

At my disposal is PHP, Javascript, JQuery but I'd kill for a CSS-only solution. I don't care if it doesn't work in IE.

Thank you




Here is the current best solution I have, using JQuery, inspired from gutierrezalex reply below. The idea is to give a height to the image container so that the
max-height
just works as expected:

<!DOCTYPE html>
<html>
<head>
<style>
* {
padding: 0;
margin: 0;
}
.fit {
max-width: 100%;
max-height: 100%;
}
.center {
display: block;
margin: auto;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" language="JavaScript">
function set_body_height()
{
var wh = $(window).height();
$('body').attr('style', 'height:' + wh + 'px;');
}
$(document).ready(function() {
set_body_height();
$(window).bind('resize', function() { set_body_height(); });
});
</script>
</head>
<body>
<img id="the_pic" class="center fit" src="pic.jpg" >
</body>
</html>

Answer Source

The solution, using JQuery, is to set the height to the image container (body in the example below) so that the max-height property on the image just 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download