Full Screen Background Image Is Stretched

后端 未结 6 1219
我在风中等你
我在风中等你 2021-01-07 02:58

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:

6条回答
  •  鱼传尺愫
    2021-01-07 03:30

    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"

提交回复
热议问题