使用 CSS calc() 数学方法计算高度

Height calculation with CSS calc() math method

我的应用程序中存在 CSS 布局问题,您可以在此处重现 jsFiddle

基本上,它很简单,如下所示:

html,body {
    height: 100%;
}
.header {
   background: yellow;
   height: 50px;
}
.main {
   background: green;
   height: calc(100% - 50px);
}
<div class="header">Create a div that stretches across the window, with a 50px gap between both sides of the div and the edges of the window:</div>
<div class="main"></div>

表头div用50px设置为固定高度,我想让主div占据剩余的高度,所以我用calc(100% - 50px)

但结果对我来说有点奇怪。生成的高度不准确,生成了垂直滚动条。我已经检查了边距或填充,没有问题。

我想要的结果是整个页面 div分成两部分。并且没有产生滚动条。

浏览器默认设置了一些margin(大约8px),请将其重置为0

html,body {
  height: 100%;
}
body {
  margin: 0;
}
.header {
  background: yellow;
  height: 50px;
}
.main {
  background: green;
  height: calc(100% - 50px);
}
<div class="header">Create a div that stretches across the window, with a 50px gap between both sides of the div and the edges of the window:</div>
<div class="main"></div>

正如@Pangloss 上面所说,浏览器会自动向导致该问题的页面添加边距。防止这种情况和其他不同浏览器怪癖的一个好方法是在 CSS 构建过程中使用 Normalize.css<head>.

中的 CDN link