csscss-calc

Height calculation with CSS calc() math method


I have a CSS layout issue in my application, you can reproduce it here with jsFiddle.

Basically, it is quite simple as following:

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>

The header div is set to fixed height with 50px, and I want the main div to occupy the remaining height, so I use calc(100% - 50px).

But the result is a little strange for me. The produced height is not accurate, and a vertical scrollbar was generated. And I have checked the margin or padding, no problem.

My desired result is the whole page divided into two parts. And no scroll bar produced.


Solution

  • There is some margin (about 8px) set by the browser by default, reset that to 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>