首页 > 解决方案 > 背景尺寸封面不适用于移动设备上的较长页面

问题描述

这是一个 Next.js 项目,这里使用的移动设备是 google pixel 3a。我有一个问题,在较长的页面上我的背景图像根本不会显示。这是它在高度不超过视口高度的页面上的外观 在此处输入图像描述

但是在一些需要滚动到底部的较长页面上,它根本不显示

在此处输入图像描述

body {
  background-image: url("https://via.placeholder.com/500");
  background-size: cover;
  margin: 0;
  padding-left: 5vw;
  padding-right: 5vw;
  height: 100vh;
  min-height: 100%;
  width: 90vw;
  font-family: system-ui;
  overflow-x: hidden;
  font-size: 1.3rem;
}

如果我将背景大小更改为自动,那么它将适用于每一页,但我想要封面。也许我不明白封面对于需要滚动的页面是如何工作的,但我希望背景图像显示为第一张图像中的样子,如果内容比视口长,则内容应该只滚动图像没有移动。任何帮助表示赞赏。谢谢。

标签: javascriptcssreactjsnext.js

解决方案


If I've understood correctly, you want the background image to at least fill the viewport but if the body is higher than that you want it to fill the whole body.

Therefore, tell it that the min-height of the body must be 100vh and don't set an actual height, let it work it out from the content.

I'm assuming in this snippet that you want just one copy of the background, centered and using size cover (so it may get cropped top/bottom or at the sides depending on relative aspect ratios).

A dummy div is put in the snippet to ensure we get scrolling.

body {
  background-image: url("https://via.placeholder.com/500");
  background-size: cover;
  background-repeat: no-repeat no-repeat;
  background-position: center center;
  margin: 0;
  padding-left: 5vw;
  padding-right: 5vw;
  min-height: 100vh;
  width: 90vw;
  font-family: system-ui;
  overflow-x: hidden;
  font-size: 1.3rem;
}

div {
  height: 350vh;
}
<div></div>


推荐阅读