如何在移动浏览器中制作固定背景以覆盖整个屏幕

How to make fixed background to cover entire screen in mobile browsers?

本文关键字:背景 覆盖 屏幕 移动 浏览器      更新时间:2023-09-26

我正在使用以下CSS黑客

html { 
    background: url(background.jpg) no-repeat center center fixed;
    webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}    

但是当使用移动浏览器时,网站的高度没有覆盖整个屏幕显示! 怎么办??

您需要使页面达到屏幕的完整高度/宽度。

html,
body {
  width:100%;
  height:100%;
}

除了指定高度和宽度外,请注意某些移动浏览器不支持"背景附件:固定"。查看完整的浏览器支持列表(单击底部的"已知问题"选项卡)。

在移动设备上解决此问题的一种方法是使用媒体查询恢复为移动宽度的"背景附件:滚动"。例如:

如果你的原始 CSS 是

#some-div
{
     background: url("background.jpg") no-repeat center fixed;
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover;
}

然后,媒体查询可能如下所示:

@media (min-width : 320px) and (max-width : 767px) 
{
    #some-div {
        background-attachment: scroll;
    }
}

当然,如果您首先不需要"背景附件:固定",那么只需从第一行中删除"固定"可能会有所帮助。