Search code examples
javascripthtmlimageautoresize

Auto-resize image to fit the browser


I have a site which provides "random" pictures of different dimensions, some if not most pictures happen to not fit the browser, so I'd like to know a way to resize it to fit the browser view without scrolling, so why not the guys of Stack Overflow!

Obviously keeping proportions, I tried https://github.com/gutierrezalex/photo-resize/ but didn't work as expected.
So it's a html page with some text, the image in the middle and some other text under it.
All I want is for scrolling to be not able to use since the image should be shrunk enough to do so.


Solution

  • You don't need any JavaScript or hacks to achieve that kind of image scaling – simple CSS and HTML will just work fine. (BTW also on iPad and iPhone.)

    You can just place your img with CSS-attribute height:100%; and it will have the height of the father node in the DOM-tree. Make sure, that node (usually a div) will be properly positioned in the browser window.

    Try something like this:

    <div style="position:fixed; height: 100%; width: 100%; top:0;left 0;">
      <img src='whatever.png' style="height: 100%" />
    </div>
    

    Check out this page as a demo: andrehelbig.fotograf.de. Here the background image will always scale proportionally to fill the whole browser window (don't get irritated by the JS scrolling).

    Hope that gives a little help.