即使放大/缩小,CSS主体背景图像也固定为全屏

时间:2010-08-29 11:20:40

标签: css

我正在尝试使用CSS实现类似的功能:

我想将全身背景图像固定在全屏上,这可以通过以下代码完成:

body
{
    background: url(../img/beach.jpg) no-repeat fixed 100% 100%;
}

现在我可以验证窗口确实已经填满了该图像,至少这可以在我的Firefox 3.6上运行

然而,当我尝试放大/缩小(ctrl + - / +)时它会搞砸,当页面缩放时图像会被拉伸/收缩。

有没有更好的方法纯粹使用CSS?我没有找到背景图像的好属性。

或者我应该开始考虑jQuery来动态操纵宽度和高度?他们都被设定为100%所以我认为应该“一如既往”:(

提前感谢任何建议!

6 个答案:

答案 0 :(得分:56)

还有另一种技术

使用

background-size:cover

就是这样 完整的CSS集是

body { 
    background: url('images/body-bg.jpg') no-repeat center center fixed;
    -moz-background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
} 

最新的浏览器支持默认属性。

答案 1 :(得分:24)

我之前使用过these techniques,但两者都运作良好。如果你阅读了每个的优点/缺点,你可以决定哪个适合你的网站。

如果您想远离上述错误,可以使用full size background image jQuery plugin

答案 2 :(得分:2)

在您的css文件中添加:

.custom_class
 {
    background-image: url(../img/beach.jpg);
    -moz-background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
 }

然后,在你的.html(或.php)文件中调用这个类:

<div class="custom_class">
   ...
</div>

答案 3 :(得分:1)

以下是缩放时整页背景图像的简单代码 你只需在风格/ css中应用width:100%

position:absolute; width:100%;

答案 4 :(得分:1)

你可以用普通的css做很多事情...... css属性background-size可以像Ranjith所指出的那样设置为许多东西以及cover

background-size: cover设置缩放图像以覆盖整个屏幕,但如果屏幕和图像的宽高比不同,可能意味着某些图像不在屏幕上。

一个很好的选择是background-size: contain,它调整背景图像的大小以适应较小的宽度和高度,确保整个图像可见,但如果宽高比不同,可能会导致信箱。

例如:

body {
      background: url(/images/bkgd.png) no-repeat rgb(30,30,30) fixed center center;
      background-size: contain;
     }

我发现其他不太有用的选项是: background-size: length <widthpx> <heightpx>设置背景图像的绝对大小。 background-size: percentage <width> <height>背景图片是窗口大小的百分比。 (见w3schools.com's page

答案 5 :(得分:1)

像这样直接使用

.bg-div{
     background: url(../img/beach.jpg) no-repeat fixed 100% 100%;
}

或单独调用CSS,如

.bg-div{
    background-image: url(../img/beach.jpg);
    -moz-background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}