Search code examples
htmlcssbackgroundbackground-size

CSS background-size property


I want to add a full-size background to my website, preferably only using the CSS properties background and background-size. Currently I am using the following

.bg {
  background: url("./gfxGeneral/backgroundImage.jpg");
  background-size: cover;
  background-repeat: no-repeat;
}

And then <body class="bg"> to apply it. The issue is that if the window becomes very narrow, the landscape style background image I am using, only covers a small part, since it is scaling itself to 100% of the width. Is there anyhow I can get it to use either 100% width or 100% height, in a way that never leaves any white background? I have found some guides for this, but all of them involves rather "ugly" code.

Bonus request: Preferably using code that supports older browsers like IE9


Solution

  • What the other answers are proposing only works if your body element is as big as the window.

    If the body size is not the full window size, you could try using JavaScript (I'm using the jQuery framework):

    <script>
    $(document).ready(function() {
        // Call the function at the beginning, in case the window is already too small, 
        onResize();
    
        $(window).resize(function() {
            onResize();
        });
    
        function onResize() {
            // Note: 16 / 9 is the resolution of the background image
            // Change appropriately
            if ($(window).width() / $(window).height() < 16 / 9) {
                $(".bg").css("background-size", "auto " + $(window).height() + "px");
            }
            else {
                $(".bg").css("background-size", "cover");
            }
        }
    });
    </script>
    

    See this JFiddle

    Hope this helps!