【问题标题】:How can I scale background image for mobile using CSS?如何使用 CSS 为移动设备缩放背景图像?
【发布时间】:2018-09-30 08:14:20
【问题描述】:

我正在尝试缩放移动设备上的背景图像,以便将高度重新缩放为设备高度的 100%,并根据需要裁剪宽度以保持纵横比。

我目前正在使用以下代码来居中并修复图像:

background: url(redlineNoText.jpg) no-repeat center center fixed;

我尝试使用background-size: cover,但它会导致图像非常大,在移动浏览器上只有一小部分可见。

我也试过background-size: auto 100%,但它导致没有背景图像。

有关问题的示例,请随时查看projectredline.org。桌面视图是我们想要的。

感谢您的帮助!

【问题讨论】:

    标签: css image background-image


    【解决方案1】:

    使用单位 VH 表示视口高度,使用单位 VW 表示视口宽度。

    我经常使用的设置是这个:

    width: 100vw;
    height: 100vh;
    background: url(../images/hero.jpg);
    background-size: cover;
    background-position: center, center;
    

    您还可以使用例如:width: calc(100vw - 100px); 为您想要达到的目标提供完美的比例。

    【讨论】:

    • 谢谢!使用 vw 和 vh 效果很好。 :) 真的很感激。
    【解决方案2】:

    也许background-attachment 可以帮助你?

     html,body {
     height:100%;width:100% }    
    
     body {
      background: url(http://via.placeholder.com/1220x1100) no-repeat center center fixed;
      background-size: auto auto;
      background-size: 100% auto;
      margin: 0;
      padding: 0 }
    
    @media screen and (max-width:800px) {
      body {
        background-size: cover;
        background-attachment:fixed }
    }
    <body>
    
              <div>
              
                    Content
              
              </div>
    
    </body>

    【讨论】:

      猜你喜欢
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      • 2011-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      相关资源
      最近更新 更多