猿问

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

嗨,我的页面上有几个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部分?



汪汪一只猫
浏览 512回答 3
3回答

四季花海

我最近有一个类似的问题,并且意识到这不是由于background-size:cover而是background-attachment:fixed。我通过使用针对iPhone的媒体查询并将background-attachment属性设置为来解决了该问题scroll。就我而言:.cover {&nbsp; &nbsp; background-size: cover;&nbsp; &nbsp; background-attachment: fixed;&nbsp; &nbsp; background-position: center center;&nbsp; &nbsp; @media (max-width: @iphone-screen) {&nbsp; &nbsp; &nbsp; &nbsp; background-attachment: scroll;&nbsp; &nbsp; }}编辑:该代码块位于LESS中,并为假定了预定义变量@iphone-screen。

杨魅力

这适用于Android 4.1.2和iOS 6.1.3(iPhone 4)以及台式机开关。为响应性网站而写。以防万一,在您的HTML头中,如下所示:<meta name="viewport" content="width=device-width, initial-scale=1.0"/>HTML:<div class="html-mobile-background"></div>CSS:html {&nbsp; &nbsp; /* Whatever you want */}.html-mobile-background {&nbsp; &nbsp; position: fixed;&nbsp; &nbsp; z-index: -1;&nbsp; &nbsp; top: 0;&nbsp; &nbsp; left: 0;&nbsp; &nbsp; width: 100%;&nbsp; &nbsp; height: 125%; /* To compensate for mobile browser address bar space */&nbsp; &nbsp; background: url(/images/bg.jpg) no-repeat;&nbsp;&nbsp; &nbsp; background-size: 100% 100%;}@media (min-width: 600px) {&nbsp; &nbsp; html {&nbsp; &nbsp; &nbsp; &nbsp; background: url(/images/bg.jpg) no-repeat center center fixed;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; background-size: cover;&nbsp; &nbsp; }&nbsp; &nbsp; .html-mobile-background {&nbsp; &nbsp; &nbsp; &nbsp; display: none;&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答