背景图片超出视窗并拉伸以适应

3
我有一个页面,我想要一个全屏背景图片。当页面正文适合视口时,这个功能可以很好地实现。我设置了html { height: 100%; } 和 body { min-height: 100%; padding-top: 70px; ... background-size: cover; }(顶部填充是为了页面头部)。当页面变得比视口大时,问题就出现了。正文会拉伸到正确的高度,但是背景附件永远不会变得比视口更大。以下是一个样例fiddle [https://jsfiddle.net/xdsgek6t/]。在实际版本中还有一个图像叠加,但是在fiddle中,即使我告诉它覆盖正文(在这个fiddle中由于子元素而达到3000px高),你也可以轻松地看到径向渐变结束的线。

html { height: 100%; box-sizing: border-box; }
body {
  overflow-y: scroll;
  padding-bottom: 30px;
  padding-top: 70px;
  background-color: #363636;
  min-height: 100%;
 background-color: #1976D2;
 background-image: radial-gradient( circle at top right, #64B5F6 0%, #1976D2 90% );
 background-repeat: no-repeat;
 background-attachment: scroll;
 background-position: right 70px;
 background-size: cover;
  margin: 0;
  box-sizing: border-box;
}
div.something { height: 3000px; width: 10px; }
header { position: absolute; width: 100%; top: 0; left: 0; height: 70px; z-index: 500; background-color: #ddd; }
<body>
  <header></header>
  <div class="something"></div>
</body>

当页面稍微变大一点时,这样做看起来非常奇怪,在移动设备上特别明显。


在HTML中添加背景颜色,body的背景颜色将被有效地绘制在body的背景上。在HTML/BODY上设置背景的有趣之处在于,当你在它们之一上设置背景时,它会在HTML上绘制。因此,为它们设置规则,不要使用透明作为背景颜色,而是任何纯色都可以。... https://jsfiddle.net/xdsgek6t/2/ - G-Cyrillus
我在之前的评论中加了一些参考链接:https://www.w3.org/TR/css3-background/#root-background - G-Cyrillus
非常有趣,感谢提供这些信息! - Adam Marr
1个回答

4

html 中删除 height: 100%;,它将得到扩展。如果您需要在 body 上使用 min-height: 100%,可以改用 min-height: 100vh,这不会依赖于 html 上的 height: 100%

html { box-sizing: border-box; }
body {
  overflow-y: scroll;
  padding-bottom: 30px;
  padding-top: 70px;
  background-color: #363636;
  min-height: 100vh;
 background-color: #1976D2;
 background-image: radial-gradient( circle at top right, #64B5F6 0%, #1976D2 90% );
 background-repeat: no-repeat;
 background-attachment: scroll;
 background-position: right 70px;
 background-size: cover;
  margin: 0;
  box-sizing: border-box;
}
div.something { height: 3000px; width: 10px; }
header { position: absolute; width: 100%; top: 0; left: 0; height: 70px; z-index: 500; background-color: #ddd; }
<header></header>
<div class="something"></div>


1
非常好,谢谢。这正是我为什么使用了100%的HTML,所以感谢你提出100vh建议的原因。 - Adam Marr
@AdamMarr 好的,没问题。 - Michael Coker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接