简体   繁体   中英

Background-Image Scaling

I am building a website and I want the background-image to scale with the page and always be the correct aspect ratio. The problem with background-size: cover or contain is that while it adjusts the width dimension correctly, if you have a browser in an aspect ratio that is taller than the background image, it begins to tile vertically.

So I thought I would write a jQuery function to get around this, and it works great for me:

$(window).resize(resizeBg);

function resizeBg(){
    var winWidth = window.innerWidth;
    var winHeight = window.innerHeight;
    var aspectRatio = winWidth/winHeight;
    var imageRatio = 1920/1200;
    if(aspectRatio < imageRatio)
        $("body").css("background-size", "auto " + winHeight + "px");
    else
        $("body").css("background-size", winWidth + "px auto");
}
resizeBg();

But before I put this live I just wanted to ask if anyone knows of better ways to do this or ways in which I can clean up this function.

Thanks.

background-size: auto; should work fine here, you just need to specify background-repeat: no-repeat; and background-position: center as well. Hope this helps.

There a few different ways to accomplish this. I typically try and stick with css. Here is just one css method.

html

<div id="bg">
  <img src="images/bg.jpg" alt="">
</div>

css

#bg {
  position: fixed; 
  top: -50%; 
  left: -50%; 
  width: 200%; 
  height: 200%;
}

#bg img {
  position: absolute; 
  top: 0; 
  left: 0; 
  right: 0; 
  bottom: 0; 
  margin: auto; 
  min-width: 50%;
  min-height: 50%;
}

On a csstricks.com post it explores all the various ways and includes the pros and cons + demos. I found it useful when I was exploring this matter.

http://css-tricks.com/perfect-full-page-background-image/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM