背景图像不会 show/are 在 iPad 或 iPhone 上拉伸

background images don't show/are stretched on iPad or iPhone

我在 github 页面上有一个 website,它在任何桌面浏览器上都能完美运行。但是,我的两个背景图片不会显示在移动设备上(我只测试了 iPad 和 iPhone,也可能只是 IOS)。我已经尝试添加媒体查询以确保 background-attachment 属性 在手持设备上设置为 scroll (我读过这有时是问题所在)。我还有媒体查询,确保图像不会太大而无法加载。这是我的 html:

<div id="image-1" class="background-image"></div>
<div id="image-2" class="background-image"></div>

这是css:

#image-1 {
  background-image: url('imgs/coding.jpg');
}
#image-2 {
  background-image: url("imgs/game.JPG");
}
@media only screen and (min-width: 500px) {
    /* For mobile phones: */
    #image-1 {
      background-image: url("imgs/coding-large.jpg");
    }
    #image-2 {
      background-image: url("imgs/game-large.jpg");
    }
}
@media not handheld {
    .background-image {
      background-attachment: fixed;
    }
}
.background-image {
  opacity: 0.8;
  background-repeat: no-repeat;
  background-attachment: scroll;
  background-size: 100% 100vh;
  height: 85vh;
}

如果我将 100vh 更改为 100%,则会加载图像,但它们在垂直方向上被严重拉伸。有什么建议吗?

您可以:

  • 使用固定位置,背景位置 center center:参见“CSS background-size: cover replacement for Mobile Safari”。
    refers to a background-attachment: fixed; as well, while remining use that viewport values (such as vh and vw) are technically supported on iOS 7 but simply do not work, hence the rodneyrehm/viewport-units-buggyfill 项目。
  • 或(不太优雅),对给定尺寸的媒体使用固定尺寸:参见“Background image not displayed properly on iPad and iPhone

看起来您的身高与背景尺寸属性和背景高度属性存在冲突。查看 CSS-Trick's post on background-sizes for a better implementation。因为看起来你想用图像覆盖页面的宽度,所以用 background-size:cover 代替。希望这有帮助。

使用这个

/* Image is centered vertically and horizontally at all times */
background-position: center center;

/* Image doesn't repeat */
background-repeat: no-repeat;

/* Makes the image fixed in the viewport so that it doesn't move when
the content height is greater than the image height */
background-attachment: fixed;

/* This is what makes the background image rescale based on its     container's size */
background-size: cover;

似乎 iPhones 忽略了 handheld 设备的 @media 规则(参见此处 Do iPhone / Android 浏览器支持 CSS @media handheld? )。如果图像不是正方形,则给定 background-size 属性 of 100% 100% 将使图像拉伸。

因此您可以使用 max-width 媒体查询来检测移动设备并将 background-attachment 设置为 scroll。并使用 background-size: cover 或背景大小:100% auto