【问题标题】:Dealing with CSS background images on screens with different aspect ratios. (16:9 -> 9:16)处理具有不同纵横比的屏幕上的 CSS 背景图像。 (16:9 -> 9:16)
【发布时间】:2017-10-09 05:43:35
【问题描述】:

我有一个带有背景图片的网页:

    body {
        background-image    : url("https://example.com/image.png");
        background-size     : cover;
        background-repeat   : no-repeat;
    }

这适用于 16:9 的屏幕,但对于手机 (9:16),图像仅覆盖(有点)屏幕的一半!

如何根据长宽比指定不同的图片?

【问题讨论】:

标签: css background-image screen-orientation aspect-ratio


【解决方案1】:

你可以试试这个。可能是你的图片位置有问题

body{
  background: url(http://www.planwallpaper.com/static/images/nature-wallpapers-hd.jpg) no-repeat top center fixed; 
   -webkit-background-size: cover;
      -moz-background-size: cover;
        -o-background-size: cover;
           background-size: cover;
}

显示这个,它可以帮助你理解background-size CSS background image to fit width, height should auto-scale in proportion

【讨论】:

    【解决方案2】:

    这总是会发生的,因为background-size: cover 浏览器会尝试用相同的背景填充元素。您仍然可以使用 background-position 进行一些调整,但在这些情况下并没有真正的帮助。

    更好的是,您可以根据屏幕大小使用媒体查询来使用不同的背景。

    有点像

    @media only screen and (max-width: 640px) {
      background: url(../images/mobile-background.jpg) no-repeat center center;
      background-size: cover;
    }
    
    @media only screen and (min-width: 641px) {
      background: url(../images/large-background.jpg) no-repeat center center;
      background-size: cover;
    }
    

    通过这种方式,您可以为这两种情况选择特定的图像,其中一些好处包括图像大小更合适,从而可以加快加载速度并减少用户的带宽消耗。这也会带来更好的 Page Speed 结果。

    【讨论】:

      【解决方案3】:

      这处理 CSS 中的纵横比:https://developer.mozilla.org/en-US/docs/Web/CSS/@media/aspect-ratio。谢谢@GabyakaG.Petrioli

      /*background image to load for 9:16 display*/
          @media (min-aspect-ratio: 9/16) {
              body {
                  background-image    : url("https://example.com/image1.png");
              }
          }
      
      /*background image to load for 16:9 display*/
          @media (min-aspect-ratio: 16/9) {
              body {
                  background-image    : url("https://example.com/image2.png");
              }
          }
      
      /*Common properties can go here*/
          body {
      
              background-size     : cover;
              background-repeat   : no-repeat;
          }
      

      【讨论】:

        猜你喜欢
        • 2019-03-19
        • 2017-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-13
        • 1970-01-01
        • 2015-05-17
        • 1970-01-01
        相关资源
        最近更新 更多