Full Screen Background Image Is Stretched

感情迁移 提交于 2019-12-04 16:41:41

You should really look into the background size property instead of using fixed images. Using 'cover' for background-size, means that the image should grow or shrink just enough to cover the whole background.

If you know the dimensions of the image. You can use a media query to change the background-size to 'auto' when it would otherwise grow beyond it's original size.

html, body {
    min-height: 100%;
}
body {
    background-image: url(http://leydenlewis.com/images/LANDING_PAGE.jpg);
    background-repeat: no-repeat;
    background-position: 0 0;
    background-size: cover;
}
@media (min-width: 1120px), (min-height: 630px) {
    body { background-size: auto; }
}

Try doing something like this:

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

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

This should get you the results you want and work in most browsers as well.

This should keep the image the correct ratio:

#bg-image{
height: auto;
width: auto;
float: left;
overflow: hidden;
position: relative;
}
<style> 
body {
background: url(http://37.media.tumblr.com/tumblr_lusitdffhf1qj5tnlo1_r1_500.gif);
background-size: 320px 600px;
background-repeat: no-repeat;
padding-top: 40px;
}
</style>

Since the questions doesn't specifically state CSS only (or NOT Javascript), here is a jQuery solution that I've worked out and have been using. I've noticed there might be an issue with mobile browsers.

//resize the background image
function resizeImage($selection){
    //get the ratio of the image
    var imageRatio = $selection.width() / $selection.height();

    //get the screen ratio
    var screenRatio = $(window).width() / $(window).height();

    //if the image is wider than the screen
    if(imageRatio > screenRatio){
        $selection.height($(window).height()); //set image height to screen height
        $selection.width($(window).height()*imageRatio); //set the correct width based on image ratio
    }

    //if the screen is wider than the image
    else{
        $selection.width($(window).width()); //set the image width to the screen width
        $selection.height($(window).width()/imageRatio); //set the correct image height based on the image ratio
    }
}

Run this whenever you want to resize the image, typically on "onresize" and "onload"

<body onresize="resizeImage($('#bgImage'))">

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!