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

Chr*_*Bao 0 css css-calc

我在我的应用程序中遇到 CSS 布局问题,并使用jsFiddle重现它。

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

html,body {
    height: 100%;
}
.header {
   background: yellow;
   height: 50px;
}
.main {
   background: green;
   height: calc(100% - 50px);
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

标题 div 设置为固定高度50px,我希望主 div 可以占据剩余的高度,所以我使用calc(100% - 50px).

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

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

Sti*_*ers 5

默认情况下,浏览器设置了一些margin(about 8px),将其重置为0.

html,body {
  height: 100%;
}
body {
  margin: 0;
}
.header {
  background: yellow;
  height: 50px;
}
.main {
  background: green;
  height: calc(100% - 50px);
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)