将两个 div 放在彼此下方时不需要的滚动条

Unwanted scrollbars when placing two divs below each other

我有两个全屏 divs,它们相对放置在彼此下方。但是当我访问该页面时,浏览器总是显示不需要的滚动条和大于 100vw 的宽度。当只有一个 div 时,整个事情就像一个魅力。在这里将不胜感激:)

    <html>
    <head>
        <link rel="stylesheet" type="text/css" href="normalize.css">
    <style>
    .section {
    position: relative;
    width: 100vw;
    height: 100vh;
    background-color: red;
    
    }
        
        .section.second {
            background-color: green;
        }
    </style>
    
    
    </head>
    <body>
    
    <div class="section">ASD1</div>
    
    <div class="section second">ASD2</div>
    
    
    
    </body>
    </html>

那是因为 BODY 元素默认有自己的边距。您需要将其设为零。你可以查看一下here (jsfiddle example).

body {   margin: 0; }

这是一个已知问题。

根据https://caniuse.com/#feat=viewport-units

"Currently all browsers but Firefox incorrectly consider 100vw to be the entire page width, including vertical scroll bar, which can cause a horizontal scroll bar when overflow: auto is set."

您可以添加以下 CSS 样式来修复它,

html, body {margin: 0; padding: 0; overflow-x:hidden;}

Example (JSBin)

首先,要删除不需要的边距和填充,您应该始终执行 CSS 重置(将所有浏览器特定属性重置为零)或 CSS 规范化(将所有属性设置为每个浏览器的默认值相同,但不为零)。出于调试目的,编写以下内容就足够了:

* {
  margin: 0;
  padding: 0;
}

在实际项目中,您绝对应该使用更好的解决方案,例如 Eric Meyer’s reset or Normalize.css

好的,现在我们设法解决了间距问题,但这仍然给我们留下了滚动条问题。有关解决方案,请查看 this post。它说

(...)the horizontal scroll is present because of the vertical scroll. which you can solve by giving max-width: 100%.

因此,这是最终的解决方案:

* {
  margin: 0;
  padding: 0;
}

.section {
  position: relative;
  width: 100vw;
  height: 100vh;
  max-width: 100%;
  background-color: red;
}

.section.second {
  background-color: green;
}
<div class="section">ASD1</div>
<div class="section second">ASD2</div>