Chris Bao
Chris Bao

Reputation: 2878

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.

Upvotes: 7

Views: 40835

Answers (2)

matt_jared
matt_jared

Reputation: 91

As @Pangloss says above, the browser automatically adds margin to the page causing that issue. A great way to prevent that and other different browser quirks is to use Normalize.css in your CSS build process or link to the CDN in the <head>.

Upvotes: 0

Stickers
Stickers

Reputation: 78716

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>

Upvotes: 10

Related Questions