0

I have an inline img that is 1280(w) x 1024(h) and is contained within a div. The divs dimensions are set 100%(w/h) of the viewport with overflow hidden.

I want to use the image as a fullscreen background and require that it fills the viewport completely regardless of dimensions with no borders showing. It must keep its aspect ratio and I would also like the image to be centered at all times. I am aware that to achieve this some of the image will be cropped.

I believe if make the image height match the viewport height and calculate the width based on the images aspect ratio this will work but I am unsure how to do this. Can anyone help?

Many thanks in advance.

mtwallet
  • 5,040
  • 14
  • 50
  • 74

3 Answers3

0

Use backstretch http://srobbin.com/jquery-plugins/backstretch/

$("#demo").backstretch("http://urltoimage.jpg");'

set #demo to 100/100% width and height

umbriel
  • 723
  • 1
  • 7
  • 22
0

Not really an answer to your question but a potential alternative -- have you tried the min-height/min-width CSS properties?

HTML:

   <div class="container">
       <div class="image-wrapper">
           <img src="..." />
       </div>
   </div>

CSS:

.container { 
    width: 100vw;
    height: 100vh;
    background-color: grey;
}

.image-wrapper {
    position: relative;
    width: 100%;
    height: 100%;
    overflow: hidden;
}

.image-wrapper img {
    position: absolute;
    top: 50%;
    left: 50%;
    min-width: 100%;
    min-height: 100%;
    transform: translateX(-50%) translateY(-50%);
}

Fiddle: https://jsfiddle.net/mkjoyep1/

In the example, .container (your full width/height div), fills the page width vw/wh and the .image-wrapper has its width/height set to 100% which will match the parent's width and height. With overflow: hidden acting as the crop mechanism you can then stretch your image to fill it's container. I've positioned the image in the center with the method explored here.

This appears to work for me on Chrome and Firefox.

*Edited to include html/css

D Hogg
  • 46
  • 4
  • Please include all relevant code in your post and **don't** just include a link to a code hosting site. Your post should stand alone from any other resource; consider what would happen if that site went down in the future! – Nathan Tuggy Aug 06 '15 at 02:46
0

If you're not 100% glued to using an img tag, you can do the following:

HTML

<div id="background"></div>

CSS

#background {
  background: url('path/to/img.jpg');
  background-size: cover;
  background-position: center center;
  width: 100vw;
  height: 100vh;
}
rrowland
  • 2,734
  • 2
  • 17
  • 32