-->

CSS3 background-size - can I guarantee coverage?

2020-07-18 05:37发布

问题:

I have a website that uses an image as its background over the entire page. In order to do this, I am using the new CSS3 spec "background-size", which is set to "cover".

background-image: url(/images/House-Remodel-Ideas2.jpg);
background-repeat: no-repeat;
background-size: cover;

Generally speaking this works well, but I noticed that if the window starts to get too narrow (and this a fairly wide image, so even 1024x768 is "too narrow") then the image stop filling the page and instead I see the background color of the page.

This kind of destroys the look of the page. While I suppose I can get creative about both the size of the image and the overall design of the page, it would be nice if this worked as expected. I'm OK with the image spilling over or getting clipped, but I'm not OK with it being too small and leaving the page background showing.

Is there a way to set this up so that doesn't happen?

An example was requested, so... here is the image I'm using: http://i.imgur.com/igLMC.jpg

And here is the HTML:

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body {
    background-image: url(house.jpg);
    background-size: cover;
    background-repeat: no-repeat;
    background-color: red;
}
</style>
</head>
<body>
</body>
</html>

I put an obnoxious red background behind the image to demonstrate the problem. If it is working properly, you should NOT see the red. So run the above, and then resize the browser so that it is very thin, and tall. You will see lots of red under the picture. THAT's the problem.

As an update, upon more testing, removing the DOCTYPE seems to fix the problem. I am not smart enough to tell you why. :)

回答1:

I haven't implemented a css-only way to do this, but I did use the backstretch jQuery plugin once, and it worked across the board. http://srobbin.com/blog/easy-full-screen-background-images-with-jquery/



回答2:

Just set the height or min-height of the html:

html {
  min-height: 100%;
}
body {
    background-image: url(http://i.imgur.com/igLMC.jpg);
    background-size: cover;
    background-repeat: no-repeat;
    background-color: red
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>

</body>
</html>