Search code examples
cssimagebackgroundsizecover

CSS issue: background taller than screen


I'm making a website but I have a problem with the background. I use {background-size: cover;} to make my background fill the screen. But when the background image is taller than the screen, we can only see a small part of the image. I'd like to adjust the background to the screen: I don't want to see any blank but I want to see as much as possible of the image. I don't really know what to search and I can't find any answer to solve this. Is there anyone who can help me ?

In other words, I there are multiple backgrounds available. A random one is selected and displayed. So I'd like the background to fit the screen totally and lose the less of the image possible. With background-size cover, if the image selected is UHD for exemple, the background will be only the top-left pixels corresponding to the screen (1920x1080 for me). But I want it to fit the width or the height of the screen (be smaller, adaptive) to display almost the full image.

Here is the code in the CSS :

body {
    background: url('https://profuder.com/images/backgrounds/8.jpg');
    background-size: cover;
}

This image is large so I only see the top-left.

Thanks for the help.


Solution

  • I solved my issue.

    I don't really know why but the JavaScript I used for finding a random background deleted the initial

    background-size: cover;
    

    in the CSS file.

    So I just added

    document.body.style.backgroundSize = "cover";
    

    just after my code to apply a new random background

    document.body.style.background = "url('" + randomImage + "') no-repeat 0 0";
    


    Thanks for your help and sorry for the lack of code.

    Regards,
    Bastien.