【问题标题】:CSS body background image fixed to full screen even when zooming in/out即使在放大/缩小时,CSS 主体背景图像也固定为全屏
【发布时间】:2018-03-06 14:52:07
【问题描述】:

我正在尝试用 CSS 实现这样的目标:

我想将正文背景图像保持在全屏状态,这可以通过以下代码完成:

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

现在我可以验证窗口确实被该图像填满了,至少这适用于我的 Firefox 3.6

但是,当我尝试放大/缩小 (ctrl+-/+) 时,它搞砸了,图像只是在页面缩放时被拉伸/缩小。

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

或者我应该开始考虑 jQuery 来动态控制宽度和高度?它们都设置为 100%,所以我认为这应该“像往常一样”工作:(

提前感谢您的任何建议!

【问题讨论】:

标签: css


【解决方案1】:

还有一个技巧

使用

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;
} 

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

【讨论】:

    【解决方案2】:

    我之前使用过these techniques,它们都运行良好。如果您阅读了每种方法的优缺点,您可以决定哪种方法适合您的网站。

    如果您想摆脱上述错误,也可以使用full size background image jQuery plugin

    【讨论】:

    • 糟糕!从来没想过会有一个 jQuery 插件来做这件事:)
    • @Michael 我发现几乎所有东西都有一个 jQuery 插件 ;)
    【解决方案3】:

    你可以用普通的 css 做很多事情......正如 Ranjith 指出的那样,css 属性 background-size 可以设置为许多东西,就像 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

    【讨论】:

      【解决方案4】:

      将此添加到您的 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>
      

      【讨论】:

        【解决方案5】:

        这是缩放时整页背景图像的简单代码 你只需在 style/css 中应用 width:100% 就可以了

        position:absolute; width:100%;

        【讨论】:

          【解决方案6】:

          直接这样使用

          .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;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-05-25
            • 2014-04-29
            • 2023-04-03
            • 2013-02-15
            • 2016-06-20
            • 1970-01-01
            • 2011-10-14
            相关资源
            最近更新 更多