CSS3 background-size - can I guarantee coverage?

余生长醉 提交于 2019-12-06 06:19:59

问题


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>


来源:https://stackoverflow.com/questions/8217037/css3-background-size-can-i-guarantee-coverage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!