I had made a full screen background image for one of my clients, but the problem is that when I make the image to fit all the screen using the following css codes:
#bg-image{background: url(https://unsplash.com/photos/P3IJy9JMsiU/download?force=true) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;}
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; }
}
<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>
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.
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'))">
This should keep the image the correct ratio:
#bg-image{
height: auto;
width: auto;
float: left;
overflow: hidden;
position: relative;
}