背景图像不显示/延伸在iPad或iPhone上
问题描述:
我在github页面上有website,它可以在任何桌面浏览器上正常工作。但是,我的两个背景图像不会显示在移动设备上(我只测试过iPad和iPhone,它可能只是IOS)。我试图添加媒体查询,以确保手持设备上的background-attachment
属性设置为scroll
(我读过这有时是问题)。我也有媒体查询,以确保图像不会太大,无法加载。这里是我的html:背景图像不显示/延伸在iPad或iPhone上
<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”。
This page指background-attachment: fixed;
为好,而布雷使用该视口中技术支持iOS 7的值(如vh
和vw
),但根本不起作用,因此rodneyrehm/viewport-units-buggyfill
项目。 - 或(那么优雅),使用媒体的固定大小与给定大小:详见“Background image not displayed properly on iPad and iPhone”
答
它看起来像你的竞争与背景大小属性和你的背景height属性的高度。退房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;
答
的iPhone似乎无视handheld
设备(见这里Do iPhone/Android browsers support CSS @media handheld? )@media
规则。如果图像不是正方形,则100% 100%
的background-size
属性会使图像拉伸。
因此,您可以使用max-width
媒体查询来检测移动设备,并将background-attachment
设置为scroll
。并使用background-size: cover
或背景大小:100% auto