小编典典

CSS背景大小:移动Safari的封面替代

css

嗨,我的页面上有几个div,它们的背景图像需要扩展以覆盖整个div,而整个div又可以扩展为填充视口的宽度。

显然background-size: cover在iOS设备上的行为异常。我已经看到了一些修复方法的示例,但我无法使其在我的情况下起作用。理想情况下,我不希望<img>在HTML中不添加额外的标签,但是如果这是唯一的方法,那么我会这样做。

这是我的代码:

.section {

  margin: 0 auto;

  position: relative;

  padding: 0 0 320px 0;

  width: 100%;

}



#section1 {

  background: url(...) 50% 0 no-repeat fixed;

  background-size: cover;

}



#section2 {

  background: url(...) 50% 0 no-repeat fixed;

  background-size: cover;

}



#section3 {

  background: url(...) 50% 0 no-repeat fixed;

  background-size: cover;

}


<body>

  <div id="section1" class="section">

    ...

  </div>

  <div id="section2" class="section">

    ...

  </div>

  <div id="section3" class="section">

    ...

  </div>

</body>

问题是,考虑到浏览器的可变宽度和div中内容的可变高度,我如何才能使背景图像完全覆盖div部分?


阅读 337

收藏
2020-05-16

共1个答案

小编典典

我最近在很多移动设备视图中遇到了这个问题。

我的解决方案仍然是纯CSS后备

是三种很棒的方法,当CSS3的封面无法正常使用时,后两种是备用方法。

的HTML

<img src="images/bg.jpg" id="bg" alt="">

的CSS

#bg {
  position: fixed; 
  top: 0; 
  left: 0;

  /* Preserve aspect ratio */
  min-width: 100%;
  min-height: 100%;
}
2020-05-16