[html] 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. The image's original dimensions are unknown, and may or may not already fit the browser window.
  3. The image is vertically and horizontally centered.
  4. The image proportions must be conserved.
  5. The image must be displayed in its entirety in the window (no cropping.)
  6. I do not wish scrollbars to appear (and they shouldn't if the image fits.)
  7. The image automatically resizes when the window dimensions change, to occupy all the available space without being larger than its original size.

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.

This question is related to html css

The answer is


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.


Use this code in your style tag

<style>
html {
  background: url(imagename) no-repeat center center fixed;
  background-size: cover;
  height: 100%;
  overflow: hidden;
}
</style>

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>

I had a similar requirement, and had to do it it basic CSS and JavaScript. No JQuery available.

This is what I got working.

<html>
      <head>
            <style>
                   img {
                          max-width: 95% !important;
                          max-height: 95% !important;
                       }
            </style>
            <script>
                   function FitImagesToScreen() {
                      var images = document.getElementsByTagName('img');
                      if(images.length > 0){
                         for(var i=0; i < images.length; i++){
                             if(images[i].width >= (window.innerWidth - 10)){
                                 images[i].style.width = 'auto';
                               }
                            }
                         }
                   }
             </script>
      </head>
      <body onload='FitImagesToScreen()'>
      ----    
      </body>
</html>

Note : I haven't used 100% for image width as there was always a bit of padding to be considered.


My general lazy CSS rule:

.background{
width:100%;
height:auto;
background: url('yoururl.jpg') no-repeat center;
background-position: 50% 50%;
background-size: 100% cover!important;
overflow:hidden;
}

This may zoom in on your image if it is low-res to begin with (that's to do with your image quality and size in dimensions. To center your image, you may also try (in the CSS)

display:block;    
margin: auto 0; 

to center your image

in your HTML:

<div class="background"></div>

I know there's already a few answers here, but here is what I used:

max-width: 100%;
max-height: 100vh;
width: auto;
margin: auto;

If you are willing to put a container element around your image, a pure CSS solution is simple. You see, 99% height has no meaning when the parent element will extend vertically to contain its children. The parent needs to have a fixed height, say... the height of the viewport.

HTML

<!-- use a tall image to illustrate the problem -->
<div class='fill-screen'>
    <img class='make-it-fit' 
         src='https://upload.wikimedia.org/wikipedia/commons/f/f2/Leaning_Tower_of_Pisa.jpg'>
</div>

CSS

div.fill-screen {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    text-align: center;
}

img.make-it-fit {
    max-width: 99%;
    max-height: 99%;
}

Play with the fiddle.


Make it simple. Thanks

_x000D_
_x000D_
.bg {_x000D_
  background-image: url('https://images.unsplash.com/photo-1476820865390-c52aeebb9891?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80');_x000D_
  background-repeat: no-repeat;_x000D_
  background-size: cover;_x000D_
  background-position: center;_x000D_
  height: 100vh;_x000D_
  width: 100vw;_x000D_
}
_x000D_
<div class="bg"></div>
_x000D_
_x000D_
_x000D_


Resize Image to Fit the Screen by the Longest Side maintaining its Aspect Ratio

img[src$="#fit"] {
    width: 100vw;
    height: auto;
    max-width: none;
    max-height: 100vh;
    object-fit: contain;
}
  • width: 100vw - image width will be 100% of view port

  • height: auto - image height will be scaled proportionally

  • max-height: 100vw - if image height would become more than view port it will be decreased to fit the screen, consequently image width will be decreased because of the following property

  • object-fit: contain - the replaced content is scaled to maintain its aspect ratio while fitting within the element's content box

    Note: object-fit is fully supported only since IE 16.0


For the future generations, if you want a solution that answers 1-6 and does 7 in a way that allows resize beyond to original size, I have developed a complete solution for this problem:

_x000D_
_x000D_
<!DOCTYPE html>
<html>
  <body style="overflow:hidden; margin:0; text-align:center;">
    <img src="https://file-examples-com.github.io/uploads/2017/10/file_example_JPG_2500kB.jpg" style="height:100vh; max-width:100%; object-fit: contain;">
  </body>
</html>
_x000D_
_x000D_
_x000D_


width: 100%;
overflow: hidden;

I believe that should do the trick.


Building upon @Rohit's answer, this fixes issues flagged by Chrome, reliably resizes the images, and also works for multiple images that are vertically stacked, e.g. <img src="foo.jpg"><br><img src="bar.jpg"><br><img src="baz.jpg"> There is probably a more elegant way of doing this.

_x000D_
_x000D_
<style>_x000D_
    img {_x000D_
        max-width: 99vw !important;_x000D_
        max-height: 99vh !important;_x000D_
    }_x000D_
</style>_x000D_
<script>_x000D_
    function FitImagesToScreen() {_x000D_
        var images = document.getElementsByTagName('img');_x000D_
        if(images.length > 0){_x000D_
            document.styleSheets[1].rules[0].style["max-height"]=((100/images.length)-1)+"vh";_x000D_
            for(var i=0; i < images.length; i++){_x000D_
                if(images[i].width >= (window.innerWidth - 10)){_x000D_
                    images[i].style.width = 'auto';_x000D_
                }_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
</script>_x000D_
</HEAD>_x000D_
<BODY onload='FitImagesToScreen()' onresize='FitImagesToScreen()'>_x000D_
<img src="foo.png">_x000D_
</BODY>
_x000D_
_x000D_
_x000D_


html, body{width: 99%; height: 99%; overflow: hidden}
img.fit{width: 100%; height: 100%;}

Or maybe check this out: http://css-tricks.com/how-to-resizeable-background-image/