【问题标题】:White space from html below 100vh cover background image, causing scrollbar100vh以下的html空白覆盖背景图像,导致滚动条
【发布时间】:2019-12-30 20:14:39
【问题描述】:

在我的 React 项目中,我有一个用于登录页面的组件。具有“登陆”类的部分元素是组件的顶级元素。我希望背景图像占据屏幕的整个宽度,它确实如此 - 但是,封面图像下方有空白区域并出现滚动条。

设置html { overflow-y: hidden } 消除了这个问题,但我不能这样做,因为它会切断其他需要滚动条的组件的内容。 (React Router 用于显示组件——如果只有在仅显示登陆组件路由时我可以通过某种方式做到这一点......)

当我打开 Chrome 开发工具并将鼠标悬停在空白处时,会突出显示两件事:首先(向上)div#root,下面是html

节元素的CSS:

.landing {
  /* center center is background-position, cover is background-size (see https://stackoverflow.com/questions/31558245/declaring-all-css-background-properties-in-one-line-especially-background-size) */
  /* bacground-position: 2-value syntax: one value defines X and the other defines Y. Default value is top left or 0% 0% */
  background: url('./img/showcase.jpg') no-repeat center center / cover;
  height: 100vh;
}

GitHub 存储库here。登陆页面组件代码here。完整的 CSS here.

【问题讨论】:

  • 你的页面检查员怎么说?
  • Michael_B:不,body { margin: 0 } 没有效果。 html 肯定会导致问题,因为html { overlow-y: hidden } 删除了空白和滚动条。
  • html { overlow-y: hidden } 之所以有效,是因为无论如何它都会阻止出现垂直滚动条。但这并不意味着你的风格问题在于html 标签。

标签: css reactjs


【解决方案1】:

编辑:我从您的源代码构建了您的 React 站点。问题是您的登陆部分下有<section class="container"></section>.container 应用了这些样式:

.container {
    max-width: 800px;
    margin: auto;
    overflow: hidden;
    padding: 0 2rem;
    margin-top: 6rem;
    margin-bottom: 3rem;
}

因此,它占据了一些高度并导致溢出。如果您不需要该部分,请将其删除,您的问题就解决了。如果您确实需要它,那么您需要使用我在下面的答案来计算 .landing 的正确高度。

display: none; 添加到.container


100vh 的高度相当于视口的 100%,而不是 剩余的视口,而是整个视口。但是因为你有一个标题,你最终的总高度是标题+视口,导致滚动条。

您可以执行height: calc(100vh - <height_of_header>); 之类的操作,其中替换为您的 CSS 中标题的实际高度。

* {
  margin: 0;
  padding: 0;
}

header {
  background: #777;
  height: 50px;
}

.landing {
  background: #999;
  height: calc(100vh - 50px);
}
<header>
  <h1>Header</h1>
</header>

<section class="landing">
  <p>This is the landing section</p>
</section>

另外值得注意的是,如果.landing的内容超出视口,如果你只使用height,背景不会随之扩展。在这种情况下,您应该改用min-height

【讨论】:

  • 没有标题元素。完整的 CSS 在这里:github.com/nataliecardot/devconnect/blob/master/client/src/… 我还链接了登录页面组件。 position: fixed 的导航栏不会导致问题。
  • 我使用
    标签来说明演示,但在您的情况下,您的某些东西占据了高度,这就是为什么在 .layout 上使用 100vh 会导致页面太高。您的组件链接限制我们只能看到该组件的元素,我没有进去检查您的整个布局。
  • @Natalie 这个网站在任何地方吗?
  • 您添加了关于 Landing.js 没有 .container 类的评论,但您的 section 元素位于您的 Switch 组件上方并且始终呈现。该规则集中的margin 值导致出现滚动条。我认为...
  • @Natalie 我也试过了。奇怪的是,即使规范说它应该与 rem 和 em 一起使用,Chrome 似乎并不承认这一点。如果我使用像素值,它确实有效。
猜你喜欢
  • 2016-04-17
  • 1970-01-01
  • 2013-10-09
  • 2018-07-20
  • 2012-09-08
  • 2014-10-03
  • 1970-01-01
  • 1970-01-01
  • 2013-08-07
相关资源
最近更新 更多